{"record":{"id":"b7eb38e504507069","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"images-is-expected-to-be-a-list-of-3d-tensors-of-s","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":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/faster_rcnn/network_files/transform.py","lineNumber":243,"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)  # 将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":225,"sourceCodeEnd":261,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/faster_rcnn/network_files/transform.py#L225-L261","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"// before\noutputs = model(batch_tensor)  # batch_tensor: [N, C, H, W]\n// after\nimages = [img for img in batch_tensor]\ntargets = [{...} for _ in images]\noutputs = model(images, targets)","handlingStrategy":"validation","validationCode":"images = [img for img in batch]\nassert all(torch.is_tensor(img) and img.dim() == 3 for img in images), \"each image must be [C, H, W]\"\noutputs = model(images, targets)","typeGuard":"def is_valid_image_list(images) -> bool:\n    return isinstance(images, list) and all(\n        torch.is_tensor(i) and i.dim() == 3 and i.shape[0] in (1, 3) for i in images\n    )","tryCatchPattern":"try:\n    outputs = model(images, targets)\nexcept ValueError as e:\n    if \"3d tensors\" in str(e):\n        images = [img.squeeze(0) if img.dim() == 4 else img for img in images]\n        outputs = model(images, targets)","preventionTips":["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"],"tags":["python","valueerror","tensor-shape","data-loading"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}