WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError
images is expected to be a list of 3d tensors of shape [C, H
Error message
images is expected to be a list of 3d tensors of shape [C, H, W], got {} What it means
GeneralizedRCNNTransform.forward expects images as a list of individual 3D tensors shaped [C, H, W]. When any tensor has a different dimensionality (commonly a 4D [N, C, H, W] batched tensor), it raises ValueError with the offending shape.
Source
Thrown at pytorch_object_detection/mask_rcnn/network_files/transform.py:439
_indent = '\n '
format_string += "{0}Normalize(mean={1}, std={2})".format(_indent, self.image_mean, self.image_std)
format_string += "{0}Resize(min_size={1}, max_size={2}, mode='bilinear')".format(_indent, self.min_size,
self.max_size)
format_string += '\n)'
return format_string
def forward(self,
images, # type: List[Tensor]
targets=None # type: Optional[List[Dict[str, Tensor]]]
):
# type: (...) -> Tuple[ImageList, Optional[List[Dict[str, Tensor]]]]
images = [img for img in images]
for i in range(len(images)):
image = images[i]
target_index = targets[i] if targets is not None else None
if image.dim() != 3:
raise ValueError("images is expected to be a list of 3d tensors "
"of shape [C, H, W], got {}".format(image.shape))
image = self.normalize(image) # 对图像进行标准化处理
image, target_index = self.resize(image, target_index) # 对图像和对应的bboxes缩放到指定范围
images[i] = image
if targets is not None and target_index is not None:
targets[i] = target_index
# 记录resize后的图像尺寸
image_sizes = [img.shape[-2:] for img in images]
images = self.batch_images(images, self.size_divisible) # 将images打包成一个batch
image_sizes_list = torch.jit.annotate(List[Tuple[int, int]], [])
for image_size in image_sizes:
assert len(image_size) == 2
image_sizes_list.append((image_size[0], image_size[1]))
image_list = ImageList(images, image_sizes_list)
return image_list, targetsView on GitHub (pinned to 1ec3fe6f37)
Solutions
- Wrap images in a list of [C,H,W] tensors: model([img1, img2], targets)
- If you have a batched tensor, split it: images = [t for t in batch]
- Add a channel dimension to 2D grayscale: img.unsqueeze(0)
Example fix
// before output = model(batch_images) # batch_images: [N, C, H, W] // after output = model([img for img in batch_images], targets) # list of [C, H, W] tensors
Defensive patterns
Strategy: validation
Validate before calling
assert isinstance(images, list) and all(isinstance(t, torch.Tensor) and t.dim() == 3 for t in images), "images must be list of [C,H,W] tensors" outputs = model(images, targets)
Type guard
def is_image_list(images):
return isinstance(images, (list, tuple)) and all(torch.is_tensor(t) and t.dim() == 3 for t in images) Try / catch
try:
outputs = model(images, targets)
except ValueError as e:
if '3d tensors' in str(e):
images = [img for img in images] if torch.is_tensor(images) else [img.unsqueeze(0) for img in images]
outputs = model(images, targets)
else:
raise Prevention
- Unbatch tensors into lists before calling detection models
- Convert PIL/numpy to CHW float tensors (transforms.functional.to_tensor)
- Standardize a prepare_batch() helper for inputs
When it happens
Trigger: Passing a batched tensor model(images_tensor) where images_tensor is [N,C,H,W] instead of a list of 3D tensors, or passing a single 2D grayscale image [H,W] unwrapped.
Common situations: Forgetting to index the batch (images[0]); custom collate_fn stacking images into one tensor; feeding PIL-like [H,W] arrays without adding a channel dim.
Understand the failure class
Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.
Related errors
- images is expected to be a list of 3d tensors of shape [C, H
- expected stages_repeats as list of 3 positive ints
- expected stages_out_channels as list of 5 positive ints
- image: {} isn't RGB mode.
- not find GPU device for training.
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/1e75b2c014760039.
Report an issue: GitHub.