Scipy.misc无imresize/imread属性,求适配Google Colab的替代代码
Hey there! It’s super common to hit this deprecated scipy issue these days—those old scipy.misc image functions were retired a while back, so Google Colab’s up-to-date scipy install doesn’t include them anymore. Let’s swap them out for the PIL-based approach you mentioned, step by step.
Step 1: Replace scipy.misc.imread
First, we’ll replace sc.imread() with PIL’s Image.open(), which is the standard modern way to load images. We’ll also ensure the image is in RGB mode to match your original mode='RGB' parameter.
Step 2: Replace scipy.misc.imresize
For resizing, we’ll use PIL’s built-in resize() method with bilinear interpolation, then convert back to a numpy array and cast to double precision just like your original code.
Full Modified Code
Here’s the drop-in replacement for your original snippet:
from PIL import Image import numpy as np height = 256 width = 256 channels = 3 # Load the image with PIL instead of scipy.misc.imread img = Image.open(Tr_list[idx]) # Ensure image is in RGB mode (matches your original mode='RGB') img = img.convert('RGB') # Resize with bilinear interpolation (note: PIL uses (width, height) order!) img_resized = img.resize((width, height), resample=Image.Resampling.BILINEAR) # Convert to numpy array and cast to double precision img = np.double(img_resized)
Key Notes to Avoid Gotchas:
- Dimension Order: Unlike
scipy.imresizewhich uses[height, width], PIL’sresize()takes(width, height)—don’t mix these up, or your image will be stretched incorrectly! - Interpolation:
Image.Resampling.BILINEARis the modern PIL syntax (for versions ≥9.1.0). If you’re on an older PIL version, useImage.BILINEARinstead—Colab’s current PIL should support the Resampling enum, but it’s good to keep this in mind. - RGB Conversion: The
convert('RGB')step ensures even grayscale or RGBA images get converted to 3-channel RGB, matching your originalmode='RGB'requirement.
This code will behave exactly like your original snippet but uses active, supported libraries instead of deprecated scipy functions.
内容的提问来源于stack exchange,提问作者Babak Azad

