img_name = './pikachu.jpg'
img = cv2.imread(img_name)
box = [ 140, 16,468,390, "pikachu"]
box_color = (255,0,255)
cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), color=box_color, thickness=2)
接下来我们来给矩形框添加标签,我们观察上述画图函数,注意最后一个参数thickness,
如果此值等于-1,那么将对矩形框执行填充效果.
基于此,我们来写标签美化代码,如下:
def draw_label_type(draw_img,bbox,label_color):
label = str(bbox[-1])
labelSize = cv2.getTextSize(label + '0', cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2)[0]
if bbox[1] - labelSize[1] - 3 < 0:
cv2.rectangle(draw_img,
(bbox[0], bbox[1] + 2),
(bbox[0] + labelSize[0], bbox[1] + labelSize[1] + 3),
color=label_color,
thickness=-1
)
cv2.putText(draw_img, label,
(bbox[0], bbox[1] + labelSize + 3),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0, 0),
thickness=1
)
else:
cv2.rectangle(draw_img,
(bbox[0], bbox[1] - labelSize[1] - 3),
(bbox[0] + labelSize[0], bbox[1] - 3),
color=label_color,
thickness=-1
)
cv2.putText(draw_img, label,
(bbox[0], bbox[1] - 3),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0, 0),
thickness=1
)
上述代码中, 首先计算标签文本的大小, 然后据标签文本大小进行矩形填充, 最后使用函数cv2.putText 来画出对应的标签文本.
运行效果如下:
上述添加完标签后,由于标签框和目标矩形框颜色一致,边界处不太容易区分,这里添加对角点美化的代码,代码如下:
def draw_box_corner(draw_img,bbox,length,corner_color):
# Top Left
cv2.line(draw_img, (bbox[0], bbox[1]), (bbox[0] + length, bbox[1]), corner_color, thickness=3)
cv2.line(draw_img, (bbox[0], bbox[1]), (bbox[0], bbox[1] + length), corner_color, thickness=3)
# Top Right
cv2.line(draw_img, (bbox[2], bbox[1]), (bbox[2] - length, bbox[1]), corner_color, thickness=3)
cv2.line(draw_img, (bbox[2], bbox[1]), (bbox[2], bbox[1] + length), corner_color, thickness=3)
# Bottom Left
cv2.line(draw_img, (bbox[0], bbox[3]), (bbox[0] + length, bbox[3]), corner_color, thickness=3)
cv2.line(draw_img, (bbox[0], bbox[3]), (bbox[0], bbox[3] - length), corner_color, thickness=3)
# Bottom Right
cv2.line(draw_img, (bbox[2], bbox[3]), (bbox[2] - length, bbox[3]), corner_color, thickness=3)
cv2.line(draw_img, (bbox[2], bbox[3]), (bbox[2], bbox[3] - length), corner_color, thickness=3)
通过cv2.rectangle 函数设置 thickness, 我们可以得到填充后的图像,进而利用opencv中的 cv2.add_weight 函数可以实现透明效果.
alpha = 0.8
gamma = 0
out_img = cv2.addWeighted(img,alpha,draw_img,1-alpha,gamma)