目标检测中的边界框(x,y,w,h形式转换与绘制)

目标检测中的边界框(x,y,w,h形式转换与绘制)

之前做了个关于yolov4的目标检测项目, 对这个领域产生了兴趣, 决定系统的学习一下
记录来源: 李沐老师: 动手学深度学习
在线阅读 https://zh-v2.d2l.ai/

目标检测起到的效果是找到物体的位置并且预测其类别, 效果如下图
在这里插入图片描述
我们通常使用边界框(bounding box)来描述对象的空间位置,也就是图中的蓝色框
而常见的对bounding box的描述形式有两种

  • x, y, w, h 表示了框的中心坐标/左上角坐标 + 长 + 宽
  • x1,y1,x2,y2 表示了框的左上角坐标 + 右下角坐标

边框表现形式转换

下面的函数起到了对这两种形式转换的作用


def box_corner_to_center(boxes):
    """从(左上,右下)转换到(中间,宽度,高度)"""
    x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
    cx = (x1 + x2) / 2
    cy = (y1 + y2) / 2
    w = x2 - x1
    h = y2 - y1
    boxes = torch.stack((cx, cy, w, h), axis=-1)
    return boxes


def box_center_to_corner(boxes):
    """从(中间,宽度,高度)转换到(左上,右下)"""
    cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
    x1 = cx - 0.5 * w
    y1 = cy - 0.5 * h
    x2 = cx + 0.5 * w
    y2 = cy + 0.5 * h
    boxes = torch.stack((x1, y1, x2, y2), axis=-1)
    return boxes

举例, 先给出猫和狗的框

dog_bbox, cat_bbox = [60, 45, 378, 516], [400, 114, 655, 493]
box = torch.tensor((dog_bbox, cat_bbox))
print(box)
'''
tensor([[ 60,  45, 378, 516],
        [400, 114, 655, 493]])
'''

验证一下转换的函数是否正确

print(box_center_to_corner(box_corner_to_center(box)) == box)
'''
tensor([[True, True, True, True],
        [True, True, True, True]])
'''

边框绘制

将框绘制在图像中, 这里使用的是plt.Rectangle, 使用cv2也可以达到同样的效果

def bbox_to_rect(bbox, color):
    # 将边界框(左上x,左上y,右下x,右下y)格式转换成matplotlib格式:
    # ((左上x,左上y),宽,高)
    return d2l.plt.Rectangle(
        xy=(bbox[0], bbox[1]), width=bbox[2] - bbox[0], height=bbox[3] - bbox[1],
        fill=False, edgecolor=color, linewidth=2)

在这里插入图片描述

tips 保存图片时关闭plt自带的坐标轴

d2l.plt.axis('off')
fig = d2l.plt.savefig('catdogbox.jpg')

在这里插入图片描述

全代码

import d2lzh as d2l
from PIL import Image
import torch

d2l.set_figsize()
img = Image.open('catdog.jpg')
d2l.plt.imshow(img)
d2l.plt.show()

# bbox是bounding box的缩写
# [左上角x,左上角y,右下角x,右下角y]
dog_bbox, cat_bbox = [60, 45, 378, 516], [400, 114, 655, 493]
box = torch.tensor((dog_bbox, cat_bbox))
print(box)


def box_corner_to_center(boxes):
    """从(左上,右下)转换到(中间,宽度,高度)"""
    x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
    cx = (x1 + x2) / 2
    cy = (y1 + y2) / 2
    w = x2 - x1
    h = y2 - y1
    boxes = torch.stack((cx, cy, w, h), axis=-1)
    return boxes


def box_center_to_corner(boxes):
    """从(中间,宽度,高度)转换到(左上,右下)"""
    cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
    x1 = cx - 0.5 * w
    y1 = cy - 0.5 * h
    x2 = cx + 0.5 * w
    y2 = cy + 0.5 * h
    boxes = torch.stack((x1, y1, x2, y2), axis=-1)
    return boxes


def bbox_to_rect(bbox, color):
    # 将边界框(左上x,左上y,右下x,右下y)格式转换成matplotlib格式:
    # ((左上x,左上y),宽,高)
    return d2l.plt.Rectangle(
        xy=(bbox[0], bbox[1]), width=bbox[2] - bbox[0], height=bbox[3] - bbox[1],
        fill=False, edgecolor=color, linewidth=2)


print(box_center_to_corner(box_corner_to_center(box)) == box)
'''
tensor([[True, True, True, True],
        [True, True, True, True]])
'''
fig = d2l.plt.imshow(img)
fig.axes.add_patch(bbox_to_rect(dog_bbox, 'blue'))
fig.axes.add_patch(bbox_to_rect(cat_bbox, 'red'))
d2l.plt.axis('off')
fig = d2l.plt.savefig('catdogbox.jpg')

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
这里提供一个使用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输入到网络进行检测,得到检测结果。遍历检测结果,提取目标的坐标,绘制边界和标签,最后显示结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Joker-Tong

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

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

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

打赏作者

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

抵扣说明:

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

余额充值