python 实现PIL模块在图片画线写字
from PIL import Image, ImageDraw, ImageFont# get an imagebase = Image.open('-07-19-09-48-05.jpeg').convert('RGBA')# make a blank image for the text, initialized to transparent text colortxt = Image.new('RGBA', base.size, (255,255,255,0))# get a font 需要在C:\Windows\Fonts拷贝一份字体文件 当前脚本路径下fnt = ImageFont.truetype('simhei.ttf', 40)# get a drawing contextd = ImageDraw.Draw(txt)# 需要修改 box的位置box = tuple((1203,694,1339,867))d.rectangle(box, fill=None, outline="red", width=5)# draw text, half opacity (255,0,255,255) 其中(255,0,255)是颜色,最后的255 是深浅d.text((1203,654), "label 0.98", font=fnt, fill=(255,0,255,255))# draw text, full opacity# d.text((10,60), "World", font=fnt, fill=(255,255,255,255))fillcolor = "#ff0000" #字体颜色d.text((base.size[0]-20,10), "4", font=fnt, fill=fillcolor)out = Image.alpha_composite(base, txt)out.show()
参考官方文档
https://pillow.readthedocs.io/en/stable/reference/Image.html