源码于2022.8下载。
目的:可以使用中文标签
与之前版本的yolov5的代码不同,绘制图像的函数从
plot_one_box
改成了
annotator.box_label
在新的函数中,已经可以实现从opencv转成PIL格式
我们做的工作
1、下载合适的字体
源码中默认的使用Arial.ttf字体,这种字体在显示中文的时候会出现格子异常
为了解决这个问题,首先要更换字体,在这里使用
simhei.ttf
下载链接:http://www.font5.com.cn/ziti_xiazai.php?id=151&part=1237887120&address=0
下载完成之后,将字体放到程序中,并进行font参数的更改
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='C:/Users/24986/Desktop/anquanmao/yolov5-master/font/simhei.ttf', pil=True, example='abc'):
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='C:/Users/24986/Desktop/anquanmao/yolov5-master/font/simhei.ttf' if non_ascii else font,
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需要根据自己的路径具体填写,更改完路径之后,注意更改后面的pil,默认是False,即不使用PIL将图片转化成PIL格式。但是在这里需要进行转化。
然后需要对detect.py文件进行修改。
为了操作简单,这里重新定义一个list用来保存标签
namess = ['人','头','头盔']
for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file,这个是以txt文件的结果进行保存,不过我们用不到
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
with open(f'{txt_path}.txt', 'a') as f:
f.write(('%g '* len(line)).rstrip() % line + '\n')
#这个以。图片的形式进行保存,并且在这个地方可以根据自己是否想显示某一类特定的结果,然后去显示特定的标签,可以把不想要的标签剔除掉,还可以根据具体的坐标去判断是否显示
if save_img or save_crop or view_img: # Add bbox to image
c = int(cls) # integer class
namess = ['人','头','头盔']
label = None if hide_labels else (namess[c] if hide_conf else f'{namess[c]} {conf:.2f}') #是否添加标签
annotator.box_label(xyxy, label, color=colors(c, True))
if save_crop: #是否将目标框截取下来进行保存
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
这里将names改成了namess。
修改完之后就可以正确显示中文了。(本方法只是用最近版本的yolov5的代码)