实例分享,真实可用
import os.path import cv2def image_rectangle_putText(result_list, src_images_path, out_images_path, confidence_threshold=0.5, type=0): """ 把识别结果result 标注到图片上 :param result_list: 识别结果,格式为[{'name': 'video', 'location': [95, 436, 147, 478], 'confidence': 0.853},{'name': 'video', 'location': [95, 436, 147, 478], 'confidence': 0.853}] :param src_images_path: 需要被标注的图片路径 :param out_images_path: 标注后保存的图片,可以和原图片一样,不过,原图片会被覆盖 :param confidence_threshold: 识别可信度,低于这个值的结果不标注在图片上 :param type: 0:全部显示 1:只显示框 2:只显示框 和 可信度 3: 只显示 框 和 名称 :return: """ img = cv2.imread(src_images_path) for oneresult in result_list: # oneresult:{'name': 'video', 'location': [95, 436, 147, 478], 'confidence': 0.853} name = oneresult["name"] # 类别名称 xmin, ymin, xmax, ymax = oneresult["location"] confidence = oneresult["confidence"] # 置信度 if confidence <= confidence_threshold: # 不满足阈值要求,跳过 continue # 画矩形框 距离靠左靠上的位置 pt1 = (xmin, ymin) # 左边,上边 #数1 , 数2 pt2 = (xmax, ymax) # 右边,下边 #数3,数4 cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2) b, g, r = img[ymin - 2, xmin - 2] # [y, x] b, g, r = 255 - b, 255 - g, 255 - r # 标注颜色 按照 相反的颜色显示 font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体 if type == 0: yourtext = '{:.3f}:{}'.format(confidence, name) elif type == 1: yourtext = '' elif type == 2: yourtext = '{:.3f}'.format(confidence) elif type == 3: yourtext = '{}'.format(name) else: raise ("type is error") img = cv2.putText(img, yourtext, (xmin - 9, ymin - 9), font, 0.6, (int(b), int(g), int(r)), 1) # 图像, 文字内容, 坐标(右上角坐标),字体, 大小(百分比), 颜色, 字体厚度 cv2.imwrite(out_images_path, img) print("out_images_file is saved to {}".format(out_images_path))if __name__ == "__main__": images_path = r"D:\AI\wll2\btn_add1.png" result_list = [{'name': 'video', 'location': [95, 436, 147, 478], 'confidence': 0.853}, {'name': 'video', 'location': [433, 168, 472, 196], 'confidence': 0.015}] base_dir = os.path.dirname(images_path) basename, images_type = os.path.basename(images_path).split('.') out_images_path = os.path.join(base_dir, basename + '_new.' + images_type) image_rectangle_putText(result_list, src_images_path=images_path, out_images_path=out_images_path, type=0)
1462

被折叠的 条评论
为什么被折叠?



