使用torchvision.draw_bounding_boxes绘制边界框位置偏移问题求助
边界框绘制错误修复方案
核心问题原因
你使用torchvision.utils.draw_bounding_boxes时边界框坐标构造不符合接口要求:
该接口要求输入的边界框格式为[x_min, y_min, x_max, y_max],其中:
- x 对应图像水平宽度方向,x_min为左边界、x_max为右边界,计算方式为
x_max = left + width - y 对应图像垂直高度方向,y_min为上边界、y_max为下边界,计算方式为
y_max = top + height
你当前代码中错误交换了宽度、高度对应的坐标轴,导致边界框位置偏移。
修正后完整代码
import torch import torchvision from PIL import Image import matplotlib.pyplot as plt img = Image.open("/content/drive/MyDrive/58125_000893_Sideline_frame298.jpg").convert('RGB') convert_tensor = torchvision.transforms.ToTensor() img = convert_tensor(img) width = 15 top = 456 height = 16 left = 1099 img = img * 255 # 仅修改边界框构造逻辑即可 boxs = [left, top, left + width, top + height] print(boxs) boxs = torch.tensor(boxs, dtype=torch.int) a = torch.tensor(img, dtype=torch.uint8) a = torchvision.utils.draw_bounding_boxes(image=a, boxes=boxs.unsqueeze(0), width=2, colors=(0,0,255)) a = a.permute(1,2,0) plt.imshow(a) plt.show()
原错误效果示意

内容的提问来源于stack exchange,提问作者Joshua Jenny Sibbu
相关产品推荐
相关产品推荐

