使用skimage inpaint_biharmonic遇ValueError:输入数组形状需一致,已确认形状仍报错
Let's break down why you're hitting this error even after verifying the shapes match, and how to fix it:
The Root Cause
Even if image_orig.shape == mask.shape returns True, there's a hidden issue with how your mask is formatted:
Skimage's inpaint_biharmonic expects the mask to be a single-channel (grayscale) array, where non-zero pixels mark the areas to inpaint. Your mask is a PNG file, which is likely saved as a 3-channel (RGB) or 4-channel (RGBA) image. Even though the shape matches your 3-channel original image, the function doesn't recognize a multi-channel array as a valid mask.
Step-by-Step Fix
Here's how to adjust your code to meet the function's requirements:
Load the mask as a single-channel grayscale image
Usecv2.IMREAD_GRAYSCALEto force the mask into a 2D array (no color channels):import cv2 from skimage.restoration import inpaint # Load original image (3-channel BGR) image_orig = cv2.imread('R.jpg') # Load mask as grayscale (single-channel) mask = cv2.imread('InkedR.jpg', cv2.IMREAD_GRAYSCALE)Binarize the mask (critical!)
Ensure the mask is strictly binary: non-zero values (255) for areas you want to inpaint, and 0 for areas you want to keep (your handwritten text):# Threshold the mask to get clean binary values _, mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)Verify shapes and run inpainting
Now your mask will have shape(height, width)while your original image is(height, width, 3). Thechannel_axis=-1parameter tells the function your original image uses the last axis for color channels:# Double-check shapes (optional but helpful for debugging) print(f"Original image shape: {image_orig.shape}") print(f"Mask shape: {mask.shape}") # Run inpainting image_result = inpaint.inpaint_biharmonic(image_orig, mask, channel_axis=-1)
Extra Checks If You Still Hit Issues
- Match data types: Ensure your mask has the same dtype as your original image (usually
uint8). Add this line if needed:mask = mask.astype(image_orig.dtype) - Reverse mask if needed: If you end up inpainting the wrong areas, flip the mask with
mask = 255 - maskto swap the inpaint/keep regions.
内容的提问来源于stack exchange,提问作者InterestingPenguin80

