赞
踩
1.下载SimHei.ttf(我用的这个字体,根据实际情况下载一个中文字体就行)。
参考下载地址:http://d.xiazaiziti.com/en_fonts/fonts/s/SimHei.ttf
2.在yolov7根目录新建fonts文件夹,将字体文件放入。
修改yolov7/utils/plots.py中plot_one_box函数
1.注释掉以前不支持中文的代码。
2.在plot_one_box中调用plot_one_box_PIL,解决中文显示问题。
修改后的代码如下:
def plot_one_box(x, img, color=None, label=None, line_thickness=3): # Plots one bounding box on image img color = color or [random.randint(0, 255) for _ in range(3)] c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) # 目标框 tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) # 左上角文字+背景框 # 解决中文乱码 plot_one_box_PIL(tuple((float(x[0]), float(x[1] - 1), float(x[2]), float(x[3]))), img, color, label, line_thickness) # 原始方式不支持中文 # if label: # tf = max(tl - 1, 1) # font thickness # t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] # c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 # cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled # cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) def plot_one_box_PIL(box, imgbase, color=None, label=None, line_thickness=None): rows, cols, channels = imgbase.shape # 得到原始图片尺寸 img = Image.fromarray(imgbase) draw = ImageDraw.Draw(img) line_thickness = line_thickness or max(int(min(img.size) / 200), 2) draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot if label: fontsize = max(round(max(img.size) / 80), 6) font = ImageFont.truetype("fonts/SimHei.ttf", fontsize, encoding="utf-8") txt_width, txt_height = font.getsize(label) draw.rectangle([box[0], box[1] - txt_height + 0, box[0] + txt_width, box[1]], fill=tuple(color)) draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font) newimg = np.asarray(img) # 替换原图 imgbase[0:rows, 0:cols] = newimg return newimg
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。