图片预处理报错ValueError:无法将形状(29, 84, 3)的输入数组广播至形状(100, 100, 3)的问题咨询
Hey there, let's break down what's going on here and get this sorted out quickly!
What's Causing the Error?
Your current code doesn't actually resize the input image—it just tries to directly plop the original image array into the out array's first dimension. This only works if the input image's exact dimensions match the width and height returned by self.__get_dataset_image_size().
In your case, the dataset expects 100x100 images, but your current input is 29x84. NumPy can't automatically stretch or shrink the image to fit the target shape, hence the ValueError about broadcasting failure.
How to Fix It
You need to add an explicit image resizing step before assigning the image to the output array. Here are two reliable approaches using popular Python image processing libraries:
Option 1: Using OpenCV
OpenCV has a built-in resize function that handles scaling efficiently:
import cv2 import numpy as np def preprocess(self, img): width, height = self.__get_dataset_image_size(self.dataset_name) # Resize the input image to match the dataset's required dimensions resized_img = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA) # Create the output array and assign the resized image out = np.ndarray(shape=(1, height, width, 3), dtype='uint8') out[0, ...] = resized_img return out
cv2.INTER_AREAis a great choice for downscaling (since your input is smaller than 100x100), but you can usecv2.INTER_CUBICorcv2.INTER_LINEARfor better quality if you end up upscaling images later.
Option 2: Using PIL/Pillow
If you prefer working with PIL, this approach is just as solid:
from PIL import Image import numpy as np def preprocess(self, img): width, height = self.__get_dataset_image_size(self.dataset_name) # Convert numpy array to PIL Image, resize, then convert back to numpy pil_img = Image.fromarray(img) resized_img = pil_img.resize((width, height), Image.Resampling.LANCZOS) resized_img_np = np.asarray(resized_img) # Create and populate the output array out = np.ndarray(shape=(1, height, width, 3), dtype='uint8') out[0, ...] = resized_img_np return out
Image.Resampling.LANCZOSdelivers high-quality resizing, which is great for preserving image details when scaling.
Why It Worked Before?
The reason your code ran smoothly earlier is that the images you used had dimensions that exactly matched what self.__get_dataset_image_size() returned. No resizing was needed, so the direct assignment worked without a hitch.
Don't forget to install the required library if you haven't already:
- For OpenCV:
pip install opencv-python - For Pillow:
pip install pillow
内容的提问来源于stack exchange,提问作者Fill07

