# https://blog.csdn.net/continuing1234/article/details/120139922
# https://blog.csdn.net/weixin_45914748/article/details/138718783?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-5-138718783-blog-120139922.235%5Ev43%5Econtrol&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-5-138718783-blog-120139922.235%5Ev43%5Econtrol&utm_relevant_index=10
# https://blog.csdn.net/qq_35165004/article/details/132738991
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# img--cv2打开的图像 lt--左上 rb--右下 text--文本 color-BGR格式 thick--框的宽度 text_size--文本大小
def draw_rect_and_chinese(img, lt, rb, text, color, thick=2, text_size=20):
cv2.rectangle(img, lt, rb, color, thickness=thick, lineType=cv2.LINE_AA)
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
# 参考3中有simsun.ttc的下载地址,下载后把"font/simsun.ttc"替换为ttc文件的路径即可。
fontStyle = ImageFont.truetype("font/simsun.ttc", text_size, encoding="utf-8")
draw.text((lt[0], lt[1]), text, tuple((color[2],color[1],color[0])), font=fontStyle)
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
return img
img = cv2.imread("2niu.png")
img = draw_rect_and_chinese(img, (8,29),(320,251), "牛niu1", (0,0,255))
img = draw_rect_and_chinese(img, (359,39),(605,247), "牛niu2", (255,0,0))
cv2.imwrite("result.png", img)
结果:
参考:
1、解决cv2.putText能显示中文为“????”的问题_ubuntu cv2.puttext中文显示问号-CSDN博客