问题
font = ImageFont.truetype("",size = fontsize)
报错:
OSError: cannot open resource
原因
在Windows中,会自动在系统路径中搜索字体名,而在Ubuntu中则不会,故报错。
解决方法
- 直接修改字体文件的路径,不过这一方法需要本地有font 文件,一旦换了电脑运行就需要改变路径名,很不方便,这时候可以采用方法2
- 使用 matplotlib.font_manager 来生成TTF(True Type Font)字体,具体代码如下:
import matplotlib.font_manager as fm # to create font
from PIL import Image,ImageFont,ImageDraw
# ......
# ......
# ......
fontsize = 100
font = ImageFont.truetype(fm.findfont(fm.FontProperties(family='DejaVu Sans')),fontsize)
# ......
# ......
# ......
(受这个问题的回答启发而来)