cv2.putText()绘制中文乱码,目标检测

https://www.osgeo.cn/pillow/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.ImageDraw.rectangle

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Linda Li
@Time:2020/7/23 下午9:25
"""
# coding=utf-8
# cv2解决绘制中文乱码

import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont
#区别就是local是左上角的值,但是x是左上角和右下角的值
def Chinese_plot_box(image,label,x,sizes,colour=None,line_thickness=None):
    """x是xyxy坐标
    label="人"等汉字"""
    cv2img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    pilimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pilimg)  # 图片上打印
    font = ImageFont.truetype("font/YaqiHeiBold.ttf",sizes, encoding="utf-8")

    tl = line_thickness or round(0.002 * (image.shape[0] + image.shape[1]) / 2) + 1
    # 颜色随机
    # colour = colour or [random.randint(0, 255) for _ in range(3)]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    # 这个是大框
    draw.rectangle([int(x[0]), int(x[1]), int(x[2]), int(x[3])], outline=(255, 0, 0),
                   fill=None, width=tl)
    if label:
        print(label)
        tf = max(tl - 1, 1)  # font thickness  字体大小
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 6, thickness=tf)[0]
        # 衬托字体的小矩形
        # ([xyxy],outline轮廓的颜色, fill用于填充的颜色)
        draw.rectangle([int(x[0]),int(x[1]),c1[0] + t_size[0],c1[1] - t_size[1] - 3], outline=(255,0,0),fill=(255,0,0),width=1)
        # cv2.rectangle(image, c1, c2, (0,255,0), -1)  # filled
        # 这个颜色必须是数组tuple(colour)
        draw.text(((int(x[0]), int(x[1])-23)), label, (255,255,255), font=font)
        image = cv2.cvtColor(numpy.array(pilimg), cv2.COLOR_RGB2BGR)
    return image

if __name__ == '__main__':
    im0 = cv2.imread('data/zhoujietu/dog.jpg')
    img = Chinese_plot_box(im0, label='动物', x=[523,719,641,823], sizes=20, colour=None, line_thickness=None)
    cv2.imshow('show', img)
    cv2.imwrite('output/3/dog1.jpg', img)
    if cv2.waitKey(100000) & 0xFF == ord('q'):
        cv2.destroyAllWindows()


你可能感兴趣的:(cv2.putText()绘制中文乱码,目标检测)