可视化图片时显示中文标签

# coding=UTF-8
import cv2
import glob
import os
from PIL import Image, ImageFont, ImageDraw
import numpy as np

# color = [(0,255,0), (255,255,0), (255,0,0)]
color = [(0,255,0), (255,255,0), (255,255,0)]

def show_name(img, boxes, labels, save_img_path, img_taskid, white_ch, white):

    sized = 100
    img_PIL = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    font = ImageFont.truetype('fzltxh_GBK.ttf', sized, encoding="utf-8")
    draw = ImageDraw.Draw(img_PIL)
    boxes = boxes.astype(np.int64)
    ch_label_all = []
    for i, box in enumerate(boxes):
        x_c, y_c, w, h = box[0], box[1], box[2], box[3]
        label = labels[i]
        if label.startswith('pl'):
            ch_label = 'pl' + str(label[2:])
        else:
            wid = white.index(label)
            ch_label = white_ch[wid].split(': ')[-1]

        if label == 't':
            c = color[2]
        else:
            c = color[1]
        draw.rectangle((x_c, y_c, x_c + w, y_c + h), outline=c, width=4)

        if ch_label not in ch_label_all:
            ch_label_all.append(ch_label)
            size_img = img.shape
            sized = sized
            lcl = len(ch_label)
            draw.text((int(size_img[1]/2)-sized*int(lcl/2), sized*(i+1)), ch_label, font=font, fill=color[0])

    im_save = cv2.cvtColor(np.asarray(img_PIL), cv2.COLOR_RGB2BGR)
    cv2.imwrite(os.path.join(save_img_path, img_taskid), im_save)

你可能感兴趣的:(python)