最近做了个视屏实时处理的需求,用opencv python实现视频/图像加框以及文字(支持汉字)
OpenCV添加文字的方法putText(…),添加英文是没有问题的,但如果你要添加中文就会出现“???”的乱码,需要特殊处理一下。
#主要用到cv2的两个函数,cv2.rectangle(图像, (矩形左上角坐标), (矩形右下角坐标), (矩形颜色), 线条粗细)
cv2.rectangle(frame, (left_x_up, left_y_up), (right_x_down, right_y_down), (55,255,155), 5)
#cv2.putText(图像, 要写入的内容, (文字坐标), 字体, 字号, (字体颜色), 字体粗细)
cv2.putText(frame, 'frame_%s' %frame_id, (word_x, word_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (55,255,155), 2)
使用PIL的图片绘制添加中文,可以指定字体文件,那么也就是说使用PIL可以实现中文的输出。
思路:
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
draw.text((left, top), "文字内容", textColor, font=fontText)
注:字体文件为:simsun.ttc,Windows可以在C:\Windows\Fonts下面查找。
cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
def cv2_img_add_text(img, text_str, left, top, text_color, text_size):
if isinstance(img, np.ndarray):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("msjh.ttc", text_size, encoding="utf-8")
draw.text((left, top), text_str, text_color, font=fontText)
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
cap = cv2.VideoCapture(0) # 读取视频
fps = int(round(cap.get(cv2.CAP_PROP_FPS)))
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, fps, size)
word_x = 20
word_y = 20
while cap.isOpened():
ret, frame = cap.read()
if ret:
img_PIL = Image.fromarray(frame)
text = "添加文本"
frame = cv2.cvtColor(np.asarray(img_PIL), cv2.COLOR_RGB2BGR)
frame = cv2_img_add_text(frame, text, word_x, word_y, (55, 255, 155), 40)
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()