python opencv cv2.putText()显示中文问题

完整代码如下:

(其中cv2AddChineseText为封装代码)

import cv2 as cv
from PIL import Image, ImageDraw, ImageFont
import numpy as np
# encoding:utf-8
import base64
import requests
def cv2AddChineseText(img, text, position, textColor=(0, 0, 255), textSize=15):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv.cvtColor(img, cv.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv.cvtColor(np.asarray(img), cv.COLOR_RGB2BGR)

camera=cv.VideoCapture(0)
face_detect=cv.CascadeClassifier('D:/opencv/opencv-4.7.0-windows/opencv/sources/data/haarcascades_cuda/haarcascade_frontalface_alt2.xml')
while True:
    flag,frame=camera.read()
    gray=cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
    faces=face_detect.detectMultiScale(gray)
    for x,y,w,h in faces:
        cv.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2,1)
        frame1=cv2AddChineseText(frame,"彭锁群", (x, y),(255, 0, 0), 30)
        cv.imshow("我的照片", frame1)
    key=cv.waitKey(1)
    if key==ord("q"):
        break
camera.release()
cv.destoryAllWindows()

 

posted @ 2023-04-08 23:14  小彭先森  阅读(2537)  评论(0编辑  收藏  举报