欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > 动手学深度学习(Pytorch版)代码实践 -计算机视觉-40目标检测和边界框

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

2024/10/24 8:28:00 来源:https://blog.csdn.net/weixin_46560570/article/details/140048080  浏览:    关键词:动手学深度学习(Pytorch版)代码实践 -计算机视觉-40目标检测和边界框

40目标检测和边界框

import torch
from PIL import Image
import matplotlib.pylab as plt
from d2l import torch as d2lplt.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) / 2cy = (y1 + y2) / 2w = x2 - x1h = y2 - y1boxes = 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 * wy1 = cy - 0.5 * hx2 = cx + 0.5 * wy2 = cy + 0.5 * hboxes = 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()

运行结果:
在这里插入图片描述
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com