图片画框和标注案例

实例分享,真实可用

import os.path

import cv2
def 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)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haowll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值