cv2.putText()这个函数只能输出英文,中文输出显示在屏幕上就是????
img =cv.putText(img, text, org, fontFace,fontScale,color[, thickness[, lineType[, bottomLeftOrigin]]])
各参数依次是:图片,添加的文字,左下角坐标,字体,字体大小,颜色,字体粗细
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
# 封装函数
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(img)
# 字体的格式
fontStyle = ImageFont.truetype(
"simsun.ttc", textSize, encoding="utf-8")
# 绘制文本
draw.text(position, text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
"""
# 在图片中打印中文
img = cv2.imread('yichan.jpg')
img = cv2AddChineseText(img, '锯嘴葫芦', (100, 100), (255, 0, 0), 30)
cv2.imshow('img', img)
cv2.waitKey(0)
"""
# 在视频中打印中文
cap = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
while cap.isOpened():
ret, frame = cap.read()
frame = cv2AddChineseText(frame, '偷偷藏不住', (100, 100), (255, 0, 0), 30)
cv2.imshow('real_time', frame)
k = cv2.waitKey(1)
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
# coding=utf-8
import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont
def cv2ImgAddText(img, text):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fillColor = (255, 0, 0)
fontStyle = ImageFont.truetype("font/simsun.ttc", 40, encoding='utf-8')
draw.text((0, 0), text, font=fontStyle, fill=fillColor)
return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR) # 转换回OpenCV格式
def main():
cap = cv2.VideoCapture(0)
frame_count = 1
success = True
while (success):
success, frame = cap.read()
frame = cv2ImgAddText(frame, "狐狸那时已是猎人")
cv2.imshow("Image", frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
# draw_img()
main()