{"record":{"id":"7938aa80f53af1fb","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"images-is-expected-to-be-a-list-of-3d-tensors-of-s-7938aa","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/retinaNet/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/retinaNet/network_files/transform.py#L225-L261","documentation":"GeneralizedRCNNTransform.forward expects each input image to be a 3-D CHW tensor (channels, height, width). If any image has dim != 3 — usually because a batched 4-D tensor or a 2-D grayscale tensor was passed — it raises ValueError with the offending shape. Normalization and resizing operate per-image, so batching must happen outside the transform.","triggerScenarios":"Passing a DataLoader-collated [B, C, H, W] batch instead of a list of 3-D tensors; loading grayscale images with PIL convert('L') yielding [H, W]; passing the raw output of cv2.imread ([H, W, C], HWC instead of CHW).","commonSituations":"Custom training loops that batch with default collate; forgetting ToTensor() or image_layout conversion; grayscale datasets; mixing image-list API (torchvision detection models) with the standard batched API of classification models.","solutions":["Pass a list of individual [C, H, W] tensors: model([img1, img2], targets) rather than a stacked batch.","Convert grayscale to RGB: Image.open(p).convert('RGB') so tensors are always 3-D.","Convert HWC to CHW: img.permute(2, 0, 1) or use transforms.ToTensor() which does it.","If you have a batched tensor, split it: [images[i] for i in range(images.shape[0])]."],"exampleFix":"// before\nimgs, targets = next(iterator)        # imgs: [B, C, H, W] stacked by collate\nmodel(imgs, targets)\n// after\nimages = [img for img in imgs]        # list of [C, H, W]\nmodel(images, targets)","handlingStrategy":"type-guard","validationCode":"assert all(isinstance(img, torch.Tensor) and img.dim() == 3 for img in images), \"each image must be a [C, H, W] tensor\"","typeGuard":"def is_chw_image(img) -> bool:\n    import torch\n    return isinstance(img, torch.Tensor) and img.dim() == 3 and img.shape[0] in (1, 3)","tryCatchPattern":"try:\n    outputs = model(images, targets)\nexcept ValueError as e:\n    if \"3d tensors of shape [C, H, W]\" in str(e):\n        images = [im.squeeze(0) if im.dim() == 4 else im.permute(2, 0, 1) if im.dim() == 3 else im for im in [batched_or_raw]]\n        outputs = model(images, targets)\n    else:\n        raise","preventionTips":["Use transforms.ToTensor() which yields CHW tensors.","Pass a list of images, never a default-collated batch tensor.","Load all images with convert('RGB') to avoid 2-D grayscale tensors.","Convert HWC (cv2/numpy) with permute(2, 0, 1) before the model."],"tags":["pytorch","object-detection","shape-mismatch","tensor"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}