用 OpenCV 标注 bounding box 主要用到下面两个工具——cv2.rectangle() 和 cv2.putText()。用法如下:
# cv2.rectangle() # 输入参数分别为图像、左上角坐标、右下角坐标、颜色数组、粗细 cv2.rectangle(img, (x,y), (x+w,y+h), (B,G,R), Thickness) # cv2.putText() # 输入参数为图像、文本、位置、字体、大小、颜色数组、粗细 cv2.putText(img, text, (x,y), Font, Size, (B,G,R), Thickness)
def plt_bboxes(img, classes, scores, bboxes, figsize=(10,10), linewidth=1.5): """Visualize bounding boxes. Largely inspired by SSD-MXNET! """ #fig = plt.figure(figsize=figsize) #plt.imshow(img) height = img.shape[0] width = img.shape[1] colors = dict() for i in range(classes.shape[0]): cls_id = int(classes[i]) if cls_id == 15: score = scores[i] if cls_id not in colors: colors[cls_id] = (random.random(), random.random(), random.random()) ymin = int(bboxes[i, 0] * height) xmin = int(bboxes[i, 1] * width) ymax = int(bboxes[i, 2] * height) xmax = int(bboxes[i, 3] * width) #rect = plt.Rectangle((xmin, ymin), xmax - xmin, #ymax - ymin, fill=False, #edgecolor=colors[cls_id], #linewidth=linewidth) #plt.gca().add_patch(rect) class_name = str(cls_id) img=cv2.rectangle(img,(xmin,ymin),(xmax,ymax),(0,255,0),2) s = ‘person/%.3f‘ % (score) img=cv2.putText(img,s,(xmax+2,ymin-2), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0,255,0), 1) cv2.imwrite(‘new.jpg‘, img) cv2.namedWindow(‘Detection‘) cv2.imshow(‘Detection‘,img) cv2.destroyAllWindows() if cv2.waitKey(0) #plt.gca().text(xmin, ymin - 2, #‘{:s} | {:.3f}‘.format(class_name, score), #bbox=dict(facecolor=colors[cls_id], alpha=0.5), #fontsize=12, color=‘white‘) #plt.show()