使用cv2.resize()调整图像尺寸时遇(-215)错误的技术求助
cv::resize Error (-215: ssize.width > 0 && ssize.height > 0) Hey there! Let's sort out this frustrating OpenCV resize error—it's a common gotcha, but once you know the culprits, fixing it is straightforward. Here are the most likely reasons and how to fix them:
1. Your image didn't load correctly (the #1 cause)
The error often pops up because test_image is None (meaning OpenCV couldn't read the file at all). This happens for a few reasons:
- Wrong file path (double-check relative vs absolute paths—if your script is in a different folder, the path might not be what you think)
- Corrupted image file (try opening the image in a viewer to confirm it's intact)
- Unsupported image format (OpenCV doesn't handle all rare formats)
Fix it with a quick check:
test_image = cv2.imread("your_image_file.jpg") # Always verify the image loaded before processing if test_image is None: print(f"Error: Couldn't load image! Check the path or file.") # Add logic to skip this file or exit gracefully else: # Proceed with resize resized = cv2.resize(test_image, (272, 272))
2. Your target size is invalid
The error message explicitly checks that both width and height are positive. Even if you wrote (272,272), make sure:
- You didn't accidentally pass a nested tuple like
((272,272))(though OpenCV usually handles this, it's better to stick to a single tuple(272,272)) - You're not using variables for size that accidentally evaluate to 0 or a negative number (e.g., a calculation that went wrong)
Quick validation:
target_size = (272, 272) if target_size[0] <= 0 or target_size[1] <= 0: print("Error: Target size must have positive width and height!")
3. The original image has an invalid size
In rare cases, the image loads but has a 0x0 pixel size (super corrupted files might do this). Check the shape before resizing:
print(test_image.shape) # Should output something like (480, 640, 3) for a valid color image # If this throws an error, the image didn't load correctly
Working Example
Here's a full, safe script that avoids the error:
import cv2 def resize_image(image_path, target_size=(272, 272)): # Load image img = cv2.imread(image_path) if img is None: print(f"Failed to load {image_path}") return None # Validate target size if target_size[0] <= 0 or target_size[1] <= 0: print(f"Invalid target size: {target_size}") return None # Resize and return resized_img = cv2.resize(img, target_size) print(f"Resized {image_path} from {img.shape[:2]} to {resized_img.shape[:2]}") return resized_img # Usage resized = resize_image("my_photo.jpg", (64, 64)) if resized is not None: cv2.imwrite("resized_photo.jpg", resized)
内容的提问来源于stack exchange,提问作者Paani

