目标检测后的图像上绘制边界框和标签

效果如图所示,有个遗憾就是CV2在图像上显示中文有点难,也不想用别的了,所以改成了英文,代码在下面了,一定要注意一点,就是标注文件的读取一定要根据自己的实际情况改一下,我的所有图像的标注文件是一个XML文件。

import cv2
import os
import numpy as np

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[1] + 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.rectangle(draw_img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color=label_color, thickness=1)
    return draw_img

# 读取标注文件
def read_data(data_name):
    image_label=[]
    with open(data_name, 'r') as f:
        for line in f:
            image_label.append(line)
    return image_label

def spli_lab(word):
    labs = []
    while (len(word) > 10):
        tem = [int(word[-9]),int(word[-8]),int(word[-5]),int(word[-4]),word[-1]]
        labs.append(tem)
        word = word[:-10]
    return labs

def img_ann_ply(label):
    for lab in label:
        word = lab.split()
        #获取一张图象中的标签及位置
        # !!!!!怎们分离需要根据自己存储格式改变
        img_box = spli_lab(word)
        img_name = word[0][:-2]
        # 图像文件存储为.bmp。这里因为发现有的标间存储有bug设置了一个筛选
        if img_name[-1] != 'p':
            img_name = img_name[:-1]
        image = os.path.join(inputPath, img_name)
        # img = cv2.imread(image)
        img = cv2.imdecode(np.fromfile(image, dtype=np.uint8), -1)
        # 根据数据集中缺陷的不同设置边界框的颜色
        for box in img_box:
            if box[-1] == '"虫烂"':
                box_color = (255, 0, 0)
                box[-1] = 'Insect rot'
            elif box[-1] == '"内皮"':
                box_color = (0, 0, 255)
                box[-1] = 'endothelium'
            else:
                box_color = (0, 255, 0)
                box[-1] = 'charring'

            img = draw_label_type(img, box, box_color)

        #展示图像
        cv2.imshow("banliquexain", img)
        # 延时显示,如果想要键盘控制窗口的切换可将int数字改成0
        cv2.waitKey(60)
        #为了使窗口变得连续,我们将窗口销毁注销
        # cv2.destroyAllWindows()

if __name__ == '__main__':
    inputPath = r"F:\project\*****\datasets_2000"
    dataset_root = r"F:\project\**\datasets_2000\DetectTrainData.txt"
    # 读取标注文件,注意!!!!!!
    # 这里的标注文件读取会因文件存储格式不同需要自己改动
    label=read_data(data_name=dataset_root)

    #把标注文件中每张图像分别标注并显示
    img_ann_ply(label)


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
这里提供一个使用OpenCV库实现的目标检测绘制边界标签的代码示例: ```python import cv2 # 加载目标检测模型 model = cv2.dnn.readNetFromTensorflow('path/to/model.pb', 'path/to/model.pbtxt') # 加载图像 image = cv2.imread('path/to/image.jpg') # 获取图像尺寸 (h, w) = image.shape[:2] # 构建一个blob,将图像输入到网络中进行检测 blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5) # 将blob输入到网络中进行检测,得到检测结果 model.setInput(blob) detections = model.forward() # 遍历检测结果 for i in range(0, detections.shape[2]): # 提取置信度 confidence = detections[0, 0, i, 2] # 过滤掉置信度过低的检测结果 if confidence > 0.5: # 提取目标的坐标 box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # 绘制边界标签 label = "{:.2f}%".format(confidence * 100) cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2) y = startY - 15 if startY - 15 > 15 else startY + 15 cv2.putText(image, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示结果 cv2.imshow("Output", image) cv2.waitKey(0) ``` 其中,`model`表示目标检测模型,可以根据实际需求选择不同的模型。`blobFromImage`函数将图像转换成网络所需的格式,`forward`函数将blob输入到网络中进行检测,得到检测结果。遍历检测结果,提取目标的坐标,绘制边界标签,最后显示结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值