Transferred from: https://www.cnblogs.com/arkenstone/p/6961453.html
opencv3.2 the Chinese output to the picture
The OpenCV Puttext function cannot output characters of type UTF8, so it is not possible to print Chinese to the picture. The freetype of this article can achieve the Chinese output, but the character decoding transcoding is more troublesome, and the pillow image function is relatively easy to output Chinese, so here is the practice is now the picture from the CV2 format to PIL format, plus Chinese and then converted to CV2 format output.
1. Download the Chinese Font Library
Here you can refer to the first part of the article that matplotlib output Chinese before.
2. Cv2 Turn PiL
import Image, ImageDraw, ImageFont, cv2cap = cv2.VideoCapture(0) # 从视频流中截取图片ret, im = cap.read()cv2_im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) # cv2和PIL中颜色的hex码的储存顺序不同pil_im = Image.fromarray(cv2_im)
3. Print Chinese on PIL image
= ImageDraw.Draw(pil_im) # 括号中为需要打印的canvas,这里就是在图片上直接打印font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8) # 第一个参数为字体文件路径,第二个为字体大小draw.text((0, 0), "eg:打印在这里", (0, 0, 255), font=font) # 第一个参数为打印的坐标,第二个为打印的文本,第三个为字体颜色,第四个为字体
4. PiL image to Cv2
import numpy as npcv2_text_im = cv2.cvrColor(np.array(pil_im), cv2.COLOR_RGB2BGR))cv2.imshow("Video", cv2_text_im)
Reference
Https://stackoverflow.com/questions/14134892/convert-image-from-pil-to-opencv-format
Https://stackoverflow.com/questions/13576161/convert-opencv-image-into-pil-image-in-python-for-use-with-zbar-library
Https://stackoverflow.com/questions/16373425/add-text-on-image-using-pil
Python opencv3 to pictures and Chinese