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` to be a list of individual 3-dim tensors with shape [C, H, W]. When an image tensor has another dimensionality (e.g. 4D batched tensor [N,C,H,W] or 2D grayscale), it raises ValueError with the actual shape.
Source
Thrown at pytorch_object_detection/faster_rcnn/network_files/transform.py:243
_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) # 将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
- Unbatch: convert a [N,C,H,W] batch into a list with `[img for img in batch]` so each element is [C,H,W]
- Ensure each image passed to the model has 3 dimensions [C,H,W] (apply transforms.ToTensor() and squeeze any batch dim)
- Use the provided collate_fn when building DataLoaders so images stay a list of tensors
Example fix
// before
outputs = model(batch_tensor) # batch_tensor: [N, C, H, W]
// after
images = [img for img in batch_tensor]
targets = [{...} for _ in images]
outputs = model(images, targets) Defensive patterns
Strategy: validation
Validate before calling
images = [img for img in batch] assert all(torch.is_tensor(img) and img.dim() == 3 for img in images), "each image must be [C, H, W]" outputs = model(images, targets)
Type guard
def is_valid_image_list(images) -> bool:
return isinstance(images, list) and all(
torch.is_tensor(i) and i.dim() == 3 and i.shape[0] in (1, 3) for i in images
) Try / catch
try:
outputs = model(images, targets)
except ValueError as e:
if "3d tensors" in str(e):
images = [img.squeeze(0) if img.dim() == 4 else img for img in images]
outputs = model(images, targets) Prevention
- Keep images as a Python list of unbatched [C,H,W] tensors; do not stack with default collate
- Apply transforms.ToTensor() so PIL images become tensors before the model
- Use the repo-provided collate_fn for DataLoaders
When it happens
Trigger: Passing a 4D batched tensor wrapped in a list (each element still [1,C,H,W]), passing a raw PIL-derived tensor without ToTensor conversion, or feeding a 2D grayscale tensor directly into the model.
Common situations: Users call model(images_tensor_batch) with the whole DataLoader-collated batch tensor instead of a list of unbatched tensors; forgetting transforms.ToTensor(); custom collate_fn that stacks images.
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
- expected stages_repeats as list of 3 positive ints
- expected stages_out_channels as list of 5 positive ints
- image: {} isn't RGB mode.
- dataset have {} classes, but input {}
- dataset have {} classes, but input {}
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/b7eb38e504507069.
Report an issue: GitHub.