OpenCV 的 cv2.putText 方法中无法放置中文。
但是PIL 的 Image.Draw 的方法中有 draw.text 的方法是可以设置中文字体的。simsum.ttc 宋体。
OpenCV 读出的图像是np.ndarray 的图像格式。
PIL 读出的图像格式与上述有所不同。所以当图像从cv2 转到 PIL 操作时,两者的图像格式需要做一些变化。
#!/usr/bin/env python # !_*_ coding:utf-8 _*_ import face_recognition import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20): if (isinstance(img, np.ndarray)): pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(pil_img) # 字体默认在 C:\Windows\Fonts 下面,要鼠标右键查看属性 # fontStyle = ImageFont.truetype(‘simsun.ttc‘, textSize, encoding=‘utf-8‘) fontStyle = ImageFont.truetype(‘msyh.ttc‘, textSize, encoding=‘utf-8‘) draw.text((left, top), text, textColor, font=fontStyle) return cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR) face_image = face_recognition.load_image_file(‘imgs/qsz001.jpg‘) # face_recognition.load_image_file 读出的文件是RGB,而后面需要在cv2 上画框,cv2是BGR 的np.ndarray的数组文件 face_image = cv2.cvtColor(face_image, cv2.COLOR_RGB2BGR) face_locations = face_recognition.face_locations(face_image) for face_location in face_locations: print(face_location) top, right, bottom, left = face_location cv2.rectangle(face_image, (left, top), (right, bottom), (0, 255, 0), 2) face_image = cv2ImgAddText(face_image, "邱淑贞", left, bottom + 5, (255, 0, 0), 20) cv2.imshow("image", face_image) cv2.waitKey(0) cv2.destroyAllWindows()
注意 字体的路径:
字体默认在 C:\Windows\Fonts 下面,要鼠标右键查看属性

原文:https://www.cnblogs.com/xuwenwei/p/14549181.html