使用PIL实现图像四象限镜像时遇ValueError: Images do not match问题求助
Fixing
ValueError: Images do not match in PIL Four-Quadrant Mirror Function Let's walk through the issues in your code and fix them one by one — that error is almost always tied to mismatched image sizes or incorrect paste() parameters.
Key Problems in Your Current Code
- Reversed paste targets/sources: You’re trying to paste the empty
tempimage into the originalimage, while passing your mirrored quadrants as masks. That’s backwards — you should be pasting the mirrored quadrants intotemp. - Invalid
boxcoordinates: PIL’spaste()expects the box to follow(left, top, right, bottom)whereright > leftandbottom > top. Your code has boxes like(int(x/2),0,0,int(y/2))whererightis smaller thanleft, which triggers size mismatch errors. - Floating-point division: Using
x/2gives a float in Python 3, but image coordinates need to be integers. Use integer divisionx//2instead to avoid this.
Corrected Code
First, let’s assume your mirror_left (horizontal flip) and mirror_verticle (vertical flip) functions work correctly. Here’s the fixed version of your mirror_four function:
from PIL import Image def mirror_left(img): # Example horizontal flip function (adjust if your implementation differs) return img.transpose(Image.FLIP_LEFT_RIGHT) def mirror_verticle(img): # Example vertical flip function (adjust if your implementation differs) return img.transpose(Image.FLIP_TOP_BOTTOM) def mirror_four(image): x, y = image.size temp = Image.new("RGB", (x, y), "black") # Option 1: Mirror only the top-left quadrant across all four sections tl = image.crop((0, 0, x//2, y//2)) # Option 2: Mirror the full original image for each quadrant (uncomment below) # tl = image tr = mirror_left(tl) bl = mirror_verticle(tl) br = mirror_verticle(tr) # Paste each quadrant into the correct position in temp temp.paste(tl, (0, 0, x//2, y//2)) # Top-left temp.paste(tr, (x//2, 0, x, y//2)) # Top-right temp.paste(bl, (0, y//2, x//2, y)) # Bottom-left temp.paste(br, (x//2, y//2, x, y)) # Bottom-right return temp
What Changed?
- Fixed paste direction: Now we’re pasting each mirrored quadrant into the
tempimage, which is the correct target for your final combined image. - Valid box coordinates: Each box now uses valid ranges (e.g., the top-right quadrant starts at
x//2left, 0 top, and extends toxright,y//2bottom). - Integer division: Switched to
x//2andy//2to ensure we’re passing integer coordinates, which PIL requires for image positioning. - Optional quadrant crop: Added a note for two common use cases — mirroring just the top-left quadrant, or mirroring the full original image for each section.
If you still run into errors, double-check your mirror_left and mirror_verticle functions to make sure they return images with the correct size (matching the quadrant size if you’re cropping, or full size if not).
内容的提问来源于stack exchange,提问作者Godly God
相关产品推荐
相关产品推荐

