动手学深度学习(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()

运行结果:

相关推荐
菜冻鱼2 小时前
Python-pytorch-高级技巧
开发语言·人工智能·pytorch·python·深度学习·神经网络·聚类
菜冻鱼2 小时前
Python-pytorch-模型保存与加载
开发语言·人工智能·pytorch·python·深度学习·机器学习
LaughingZhu3 小时前
Product Hunt 每日热榜 | 2026-08-19
经验分享·深度学习·神经网络·百度·产品运营
小白学大数据3 小时前
CuPy vs Numba vs PyTorch:GPU 加速方案怎么选
人工智能·pytorch·爬虫·python
聪明蛋子哟4 小时前
RL训练Agentic模型实现并行多轮上下文检索:匹配前沿模型且快10倍
人工智能·深度学习·机器学习
hans汉斯5 小时前
采煤工作面隐患目标检测中YOLO11与Faster R-CNN的对比研究
人工智能·目标检测·计算机视觉·cnn·信息与通信·信号处理
bulingg5 小时前
bert输入长度有限,如何处理超长文本?
人工智能·深度学习·bert
菜冻鱼6 小时前
Python-pytorch-数据加载
开发语言·人工智能·pytorch·python·深度学习·机器学习
W_326007 小时前
Python-OpenCV 轮廓进阶:旋转最小外接矩形、图像矩求质心、嵌套层级 hierarchy、轮廓形状匹配
图像处理·python·opencv·机器学习·计算机视觉
machnerrn7 小时前
智慧交通系列(一)-十字路口车辆闯红灯检测告警抓拍系统(附含数据+源码+模型)
人工智能·python·深度学习