{"record":{"id":"1e75b2c014760039","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"images-is-expected-to-be-a-list-of-3d-tensors-of-s-1e75b2","errorCode":null,"errorMessage":"images is expected to be a list of 3d tensors of shape [C, H, W], got {}","messagePattern":"images is expected to be a list of 3d tensors of shape \\[C, H, W\\], got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/network_files/transform.py","lineNumber":439,"sourceCode":"        _indent = '\\n    '\n        format_string += \"{0}Normalize(mean={1}, std={2})\".format(_indent, self.image_mean, self.image_std)\n        format_string += \"{0}Resize(min_size={1}, max_size={2}, mode='bilinear')\".format(_indent, self.min_size,\n                                                                                         self.max_size)\n        format_string += '\\n)'\n        return format_string\n\n    def forward(self,\n                images,       # type: List[Tensor]\n                targets=None  # type: Optional[List[Dict[str, Tensor]]]\n                ):\n        # type: (...) -> Tuple[ImageList, Optional[List[Dict[str, Tensor]]]]\n        images = [img for img in images]\n        for i in range(len(images)):\n            image = images[i]\n            target_index = targets[i] if targets is not None else None\n\n            if image.dim() != 3:\n                raise ValueError(\"images is expected to be a list of 3d tensors \"\n                                 \"of shape [C, H, W], got {}\".format(image.shape))\n            image = self.normalize(image)  # 对图像进行标准化处理\n            image, target_index = self.resize(image, target_index)  # 对图像和对应的bboxes缩放到指定范围\n            images[i] = image\n            if targets is not None and target_index is not None:\n                targets[i] = target_index\n\n        # 记录resize后的图像尺寸\n        image_sizes = [img.shape[-2:] for img in images]\n        images = self.batch_images(images, self.size_divisible)  # 将images打包成一个batch\n        image_sizes_list = torch.jit.annotate(List[Tuple[int, int]], [])\n\n        for image_size in image_sizes:\n            assert len(image_size) == 2\n            image_sizes_list.append((image_size[0], image_size[1]))\n\n        image_list = ImageList(images, image_sizes_list)\n        return image_list, targets","sourceCodeStart":421,"sourceCodeEnd":457,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/transform.py#L421-L457","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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)"],"exampleFix":"// before\noutput = model(batch_images)  # batch_images: [N, C, H, W]\n// after\noutput = model([img for img in batch_images], targets)  # list of [C, H, W] tensors","handlingStrategy":"validation","validationCode":"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\"\noutputs = model(images, targets)","typeGuard":"def is_image_list(images):\n    return isinstance(images, (list, tuple)) and all(torch.is_tensor(t) and t.dim() == 3 for t in images)","tryCatchPattern":"try:\n    outputs = model(images, targets)\nexcept ValueError as e:\n    if '3d tensors' in str(e):\n        images = [img for img in images] if torch.is_tensor(images) else [img.unsqueeze(0) for img in images]\n        outputs = model(images, targets)\n    else:\n        raise","preventionTips":["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"],"tags":["python","image-preprocessing","tensor-shape"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}