Linux pillow ttf 图上写字
2025-08-13
Python
00

使用 /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc

bash
展开代码
def draw_bbox_on_pil_image(pil_image, bbox, text, color, thickness=2, font_size=12): """在PIL图片上绘制bbox和文本""" draw = ImageDraw.Draw(pil_image) # 获取图片尺寸 img_width, img_height = pil_image.size # 转换bbox格式 [x_br, y_br, x_tl, y_tl] -> [x1, y1, x2, y2] x_br, y_br, x_tl, y_tl = bbox # 将0-1000的归一化坐标转换为实际图片坐标 x_br = int(x_br * img_width / 1000) y_br = int(y_br * img_height / 1000) x_tl = int(x_tl * img_width / 1000) y_tl = int(y_tl * img_height / 1000) # 确保坐标顺序正确 x1 = min(x_tl, x_br) y1 = min(y_tl, y_br) x2 = max(x_tl, x_br) y2 = max(y_tl, y_br) # 绘制矩形框 draw.rectangle([x1, y1, x2, y2], outline=color, width=thickness) # 绘制文本 try: font = ImageFont.truetype("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", font_size) except: font = ImageFont.load_default() # 获取文本尺寸 bbox_text = draw.textbbox((0, 0), text, font=font) text_width = bbox_text[2] - bbox_text[0] text_height = bbox_text[3] - bbox_text[1] # 绘制文本背景 draw.rectangle([x1, y1 - text_height - 5, x1 + text_width + 10, y1], fill=(255, 255, 255), outline=(0, 0, 0)) # 绘制文本 draw.text((x1 + 5, y1 - text_height - 2), text, fill=(0, 0, 0), font=font) return pil_image
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Dong

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!