代码如下,随机在摄像头中添加文字
import cv2
import numpy as np
from random import randint
from PIL import Image, ImageDraw, ImageFont
COLOR = (255,0,0)
font_size = 24
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret,frame = cap.read()
width,height = frame.shape[:2]
w = randint(40,width-40)
h = randint(40,height-40)
img = Image.fromarray(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",font_size)
draw.text((w,h),"不明物体",COLOR,font=font)
pil_image = np.array(img)
frame = cv2.cvtColor(pil_image, cv2.COLOR_RGB2BGR)
cv2.imshow("win",frame)
key = cv2.waitKey(1000//30)
if (key & 0xFF == ord("q")):
break
cap.release()
cv2.destroyAllWindows()
# https://docs.opencv.org/4.8.0/d9/dfa/classcv_1_1freetype_1_1FreeType2.html
# https://blog.51cto.com/u_12865/10721866
Linux上使用fc-list :lang=zh
列举中文字体地址,如/usr/share/fonts/truetype/wqy/wqy-microhei.ttc。