来源: 1. https://deepinout.com/python_pillow_tutorial/python_pillow_writing_text_on_image.html 2. https://blog.csdn.net/qq_17498785/article/details/104858251
- 画方框的函数
a.rectangle(((x1, y1),(x2, y2)), fill=None, outline=color, width=1)
- 添加文字需要加载指定的字体,函数
a.text((xf, yf), text, font=font, fill=color)
代码
from PIL import ImageDraw
from PIL import Image
def draw_file(filename, js):
people_list = js.get("data", dict()).get("extra_info", list())
if not people_list:
return 0
#打开图片并根据坐标画框,并保存图片+显示
img = Image.open(filename) # 打开图片
a = ImageDraw.ImageDraw(img) #用a来表示
font = ImageFont.truetype('360shouhuti/360shouhuType-Regular.otf', 20)
for people in people_list:
color = (random.randint(150, 255), random.randint(150, 255), random.randint(150, 255))
color = 'black'
bbox = people.get("bbox", [0, 0, 0, 0])
x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]
# 在边界框的两点(左上角、右下角)画矩形,无填充,边框红色,边框像素为1
a.rectangle(((x1, y1),(x2, y2)), fill=None, outline=color, width=1)
xf = x1
yf = y2 + 5
text = "{}: {}".format(people.get("name", "-"), people.get("similarity", -1))
a.text((xf, yf), text, font=font, fill=color)
tm = time.localtime()
tmstr = time.strftime("%Y%m%dT%H%M%S", tm)
savefile = "rectangle/{}.jpg".format(tmstr)
os.makedirs(os.path.dirname(savefile), exist_ok=True)
print("save to file: {}".format(savefile))
img.save(savefile)