边界框
通常所用的边界框(相当于一个矩形框)有两种表示方式:
- 记录矩形左上角
(x1, y1)
和右下角(x2, y2)
- 记录矩形的中心点
(cx, cy)
和,矩形的宽w
和高h
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
复制代码
boxes[:,0]
,因为是若干个框的结果,所以在第一维度上使用:
取所有的值。
仔细学习一下这句代码:boxes = torch.stack((x1, y1, x2, y2), axis=-1)
torch.stack() 表示沿着一个新维度对输入张量序列进行连接,axis = -1
表示倒数第一个维度。
boxes
的维度是(n, 4)
,任意一个量cx, cy, w, d
的维度是(n)
,将其沿着倒数第一个维度拼接到一起,又变成了(n, 4)
。
一个比较不错的例子,用来理解torch.stack()
T1 = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
T2 = torch.tensor([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print(torch.stack((T1, T2), axis=0).shape)
print(torch.stack((T1, T2), axis=1).shape)
print(torch.stack((T1, T2), axis=2).shape)
print(torch.stack((T1, T2), axis=-1).shape)
复制代码
输出
torch.Size([2, 3, 3])
torch.Size([3, 2, 3])
torch.Size([3, 3, 2])
torch.Size([3, 3, 2])
复制代码