You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

加载COCO数据集时Resize图像遇RuntimeError的原因咨询

问题分析与解决

Error 1: RuntimeError: Trying to resize storage that is not resizable

这个错误是因为你给已经转成Tensor的图像用了Resize变换。torchvision.transforms.Resize是专门处理PIL图像的,要是先通过ToTensor()把图像转成了Tensor,再去做Resize,就会触发这个报错——Tensor的存储结构不支持直接调整大小,Resize没法对它生效。

解决办法:

  • 调整transform的顺序,把Resize放在ToTensor()前面,先给PIL图像做尺寸调整,再转成Tensor。

Error 2: RuntimeError: stack expects each tensor to be equal size, but got [3, 480, 640] at entry 0 and [3, 500, 500] at entry 1

这个错误说明dataloader在堆叠batch里的张量时,各个图像尺寸不统一。要么是Resize没正确作用到所有图像上,要么是你用了Resize(500)这种只固定短边的模式(长边按比例缩放后,不同图像的最终尺寸还是不一样),没强制统一到固定尺寸。

解决办法:

  • 如果需要固定尺寸,用Resize((height, width))指定具体宽高,比如Resize((480, 640)),确保所有图像都缩放到相同尺寸。
  • 检查数据集的transform参数是否正确传入了包含Resize的组合,确认预处理流程没遗漏或顺序错了。

正确的Transform示例

from torchvision import transforms
from torchvision.datasets import CocoDetection
from torch.utils.data import DataLoader

# 正确顺序:先Resize,再转Tensor
transform = transforms.Compose([
    transforms.Resize((480, 640)),  # 固定尺寸缩放
    transforms.ToTensor()
])

# 加载COCO数据集时传入transform
dataset = CocoDetection(root='path/to/images', annFile='path/to/annotations.json', transform=transform)
dataloader = DataLoader(dataset, batch_size=4, shuffle=True)

内容的提问来源于stack exchange,提问作者Mahtab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:47:04