yolov5-fastapi-demo更换中文标签

本章是基于yolov5-fastapi-demo项目的更改

WelkinU/yolov5-fastapi-demo: FastAPI Wrapper of YOLOv5 (github.com)

首先,因为训练的时候设置的标签是英文,换成中文要重新训练,而且使用中文训练也很繁琐要改很多东西,因此可以直接训练的时候用英文标签,然后在识别绘图的时候做一个判断直接把标签替换了。如下

if bbox["class_name"] =="旧的英文名":

       bbox["class_name"] ="新的中文名"

在server.py的plot_one_box中label就是传进来的标签

然后换成中文标签之后,发现变成乱码????

原来是OpenCV不支持中文,那我们换成draw.text来绘制

先去下载字体包msyh

msyh.ttc字体下载-msyh.ttc下载win10压缩版-绿色资源网 (downcc.com)

直接丢到根目录下

扫描二维码关注公众号,回复: 15433365 查看本文章

 然后导包

from PIL import ImageFont, ImageDraw, Image

 修改plot_one_box 的if label: 之下的内容

    if label:
        tf = max(tl - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
        font_size = t_size[1]
        font = ImageFont.truetype('msyh.ttc', font_size)
        t_size = font.getsize(label)
        c2 = c1[0] + t_size[0], c1[1] - t_size[1]
        cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA)  # filled
        img_PIL = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(img_PIL)
        draw.text((c1[0], c2[1] - 2), label, fill=(255, 255, 255), font=font)
        cv2.cvtColor(np.array(img_PIL), cv2.COLOR_RGB2BGR) 
        return cv2.cvtColor(np.array(img_PIL), cv2.COLOR_RGB2BGR)

此时标签已经成功替换成中文了 

猜你喜欢

转载自blog.csdn.net/weixin_65243968/article/details/130344783
今日推荐