动手学深度学习(Pytorch版)代码实践 -计算机视觉-40目标检测和边界框

40目标检测和边界框

python 复制代码
import torch
from PIL import Image
import matplotlib.pylab as plt
from d2l import torch as d2l

plt.figure('catdog')
img = Image.open('../limuPytorch/images/catdog.jpg')
plt.imshow(img)
plt.show()

# 边界框
#@save
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

#@save
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

# bbox是边界框的英文缩写
dog_bbox, cat_bbox = [60.0, 45.0, 378.0, 516.0], [400.0, 112.0, 655.0, 493.0]

# 通过转换两次来验证边界框转换函数的正确性
boxes = torch.tensor((dog_bbox, cat_bbox))
print(box_center_to_corner(box_corner_to_center(boxes)) == boxes)
# tensor([[True, True, True, True],
#         [True, True, True, True]])

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

# 图像上添加边界框
fig = plt.imshow(img)
fig.axes.add_patch(bbox_to_rect(dog_bbox, 'blue'))
fig.axes.add_patch(bbox_to_rect(cat_bbox, 'red'))
plt.show()

运行结果:

相关推荐
竣雄4 小时前
计算机视觉:原理、技术与未来展望
人工智能·计算机视觉
AI即插即用7 小时前
即插即用系列 | ECCV 2024 WTConv:利用小波变换实现超大感受野的卷积神经网络
图像处理·人工智能·深度学习·神经网络·计算机视觉·cnn·视觉检测
哥布林学者8 小时前
吴恩达深度学习课程四:计算机视觉 第三周:检测算法 (一)目标定位与特征点检测
深度学习·ai
m0_704887898 小时前
DAY 40
人工智能·深度学习
m0_692457109 小时前
阈值分割图像
图像处理·深度学习·计算机视觉
ys~~9 小时前
git学习
git·vscode·python·深度学习·学习·nlp·github
能源系统预测和优化研究10 小时前
创新点解读:基于非线性二次分解的Ridge-RF-XGBoost时间序列预测(附代码实现)
人工智能·深度学习·算法
لا معنى له10 小时前
目标分割介绍及最新模型----学习笔记
人工智能·笔记·深度学习·学习·机器学习·计算机视觉
Das111 小时前
【计算机视觉】03_重采样
图像处理·人工智能·计算机视觉
却道天凉_好个秋11 小时前
OpenCV(四十二):图像分割原理
人工智能·opencv·计算机视觉·图像分割