You need to enable JavaScript to run this app. 使用skimage inpaint_biharmonic遇ValueError:输入数组形状需一致,已确认形状仍报错
优惠活动
大模型
产品
解决方案
定价
更多

使用skimage inpaint_biharmonic遇ValueError:输入数组形状需一致,已确认形状仍报错

Fixing "ValueError: Input arrays have to be the same shape" in Skimage Inpainting

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:

  1. Load the mask as a single-channel grayscale image
    Use cv2.IMREAD_GRAYSCALE to 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)
    
  2. 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)
    
  3. Verify shapes and run inpainting
    Now your mask will have shape (height, width) while your original image is (height, width, 3). The channel_axis=-1 parameter 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 - mask to swap the inpaint/keep regions.

内容的提问来源于stack exchange,提问作者InterestingPenguin80

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:31:14