yolov5显示中文标签

本文章的方法采用的是在检测时识别完成之后替换标签渲染打印到图片的方法。
首先下载支持中文的字体,我采用的是simhei字体,链接如下,是自己使用的字体打包上传,亲测可用。
字体链接
将字体下载后放在v5工程下,可以新建一个Font放字体的ttf文件。
然后在utils下的plots.py中找到Annotator类,修改初始化函数(init()函数)里的字体路径,代码如下:

class Annotator:
    # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations
    def __init__(self, im, line_width=None, font_size=None, font='/data/yolov5/Font/simhei.ttf', pil=False, example='abc'):   #font='Arial.ttf'
        assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'
        non_ascii = not is_ascii(example)  # non-latin labels, i.e. asian, arabic, cyrillic
        self.pil = pil or non_ascii
        if self.pil:  # use PIL
            self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
            self.draw = ImageDraw.Draw(self.im)
            self.font = check_pil_font(font='/data/yolov5/Font/simhei.ttf' if non_ascii else font,  #font='Arial.Unicode.ttf'
                                       size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))
        else:  # use cv2
            self.im = im
        self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2)  # line width

修改代码中的两处font值。
接下来是标签替换,代码如下:

names = ["已预约 患者1","已预约 患者2","未预约"]
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
if len(det):
    # Rescale boxes from img_size to im0 size
    det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()

    # Print results
    for c in det[:, -1].unique():
        n = (det[:, -1] == c).sum()  # detections per class
        s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

在判断画面是否有标签的函数上加上names的list,顺序及数量要跟训练时的类别要对的上,比如这里我训练时的数据集yaml配置文件是这样的:

nc: 3
names: ['patient1','patient2','stranger']

如果识别到“patient1”则标签就要显示“已预约 患者1”,如果识别的是“stranger”则画面显示的是"未预约"。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值