为单张缩放图片添加AdditiveGaussianNoise遇AssertionError求代码修正
Fixing the AssertionError & Image Range Issue
First, let's address the immediate error you're seeing:
The AssertionError occurs because when you call aug(resized_img), the augmenter interprets your image array as the return_batch argument (which expects a boolean value, not a numpy array). Imgaug requires you to explicitly pass images using named arguments or wrap single images in a list (since it's designed to handle batches of images).
Solution 1: Use the images keyword parameter
This is the most straightforward fix:
augmented_image = aug(images=resized_img)
Solution 2: Wrap the image in a list
If you prefer this syntax, just remember to extract the first element (since it returns a batch list):
augmented_image = aug([resized_img])[0]
Second Critical Fix: Image Intensity Range
You'll run into a second issue even after fixing the error: skimage.transform.resize returns images with pixel values in the [0, 1] range (as floats), but your AdditiveGaussianNoise scale is set to (0, 0.2*255) (adding noise in the 0-51 range). This will push pixel values way outside the valid [0,1] range, causing artifacts or downstream errors.
You have two options to resolve this:
Option A: Convert to 0-255 uint8 format
Scale the resized image back to the standard 8-bit range before applying noise:
import numpy as np # Don't forget to import numpy resized_img = resize(imread(file_name), (224, 224)) * 255 resized_img = resized_img.astype(np.uint8)
Option B: Adjust noise scale for [0,1] range
Keep the image in float format and reduce the noise scale to match:
aug = iaa.AdditiveGaussianNoise(scale=(0, 0.2))
Full Corrected Code Example
Here's the complete code using the [0,1] range approach:
from skimage.io import imread from skimage.transform import resize import imgaug.augmenters as iaa file_name = "path/to/image.jpg" resized_img = resize(imread(file_name), (224, 224)) # Adjust noise scale to match [0,1] image range aug = iaa.AdditiveGaussianNoise(scale=(0, 0.2)) # Use named argument to avoid AssertionError augmented_image = aug(images=resized_img)
内容的提问来源于stack exchange,提问作者Tobitor

