【YOLOv5】将YOLOv5预测结果由矩形框改为透明mask
原始的YOLOv5预测结果是在图片上面绘制矩阵框,但是在视觉效果上并不明显。
因此将矩阵框的形式改为绘制透明mask。
代码实现:
修改YOLOv5工程中的utils/plots.py
部分代码,class Annotator
中的函数进行如下替换,主要是两处TODO:
def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
# Add one xyxy box to image with label
if self.pil or not is_ascii(label):
self.draw.rectangle(box, width=self.lw, outline=color) # box
if label:
w, h = self.font.getsize(label) # text width, height
outside = box[1] - h >= 0 # label fits outside box
self.draw.rectangle(
(box[0], box[1] - h if outside else box[1], box[0] + w + 1,
box[1] + 1 if outside else box[1] + h + 1),
fill=color,
)
# self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0
self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)
else: # cv2
p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
# TODO mask1-1
cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)
# self.im = self.mask_label(self.im, p1, p2, color)
if label:
tf = max(self.lw - 1, 1) # font thickness
w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height
outside = p1[1] - h >= 3
p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled
cv2.putText(self.im,
label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
0,
self.lw / 3,
txt_color,
thickness=tf,
lineType=cv2.LINE_AA)
# TODO mask1-2
def mask_label(self, img, pos1, pos2, color, thickness=-1, alpha=1, beta=0.5, gamma=0):
mask_zeros = np.zeros((img.shape), dtype=np.uint8)
mask = cv2.rectangle(mask_zeros, pos1, pos2, color, thickness)
mask_img = cv2.addWeighted(img, alpha, mask, beta, gamma)
return mask_img