You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Skimage v0.14反向掩码操作:将非掩码区域设为0或指定数值

Got it, let's figure out how to do this with scikit-image v0.14! You need to zero out (or set to any custom value) every part of the image except the masked region—exactly the opposite of your current code. Here are a few simple, reliable ways to make this work:

Method 1: Invert a Boolean Mask and Assign Values

First, let's assume your mask is a boolean array (where True marks the region you want to keep, False is the area to overwrite). You can just invert the mask and assign your target value to those regions directly:

from skimage import io

# Load your image and mask (make sure they have the same shape)
image = io.imread("your_image.png")
mask = io.imread("your_mask.png", as_gray=True).astype(bool)  # Convert mask to boolean type

# Set all non-masked regions to 0
result = image.copy()
result[~mask] = 0

# Or set to a custom value (e.g., 255 for 8-bit images)
custom_value = 255
result[~mask] = custom_value

If your mask is an integer array (0 for background, non-0 for the region to keep), just convert it to a boolean mask first:

# Convert integer mask to boolean
mask_bool = mask != 0
result = image.copy()
result[~mask_bool] = 0

Method 2: Use numpy.where for Concise Logic

For a one-liner approach, numpy.where is perfect. It lets you select values based on your mask condition in a single step:

import numpy as np

# Keep masked region values, set others to 0
result = np.where(mask, image, 0)

# Set non-masked regions to a custom value instead
custom_value = 128
result = np.where(mask, image, custom_value)

The np.where(condition, x, y) syntax means: where condition (your mask) is True, use values from x (your original image); where it's False, use values from y (0 or your custom value). No need to copy the image first—this creates the result directly.

Key Notes for Skimage v0.14

  • Match Shapes: If you're working with a color image (shape (H, W, 3)), make sure your mask matches the image's dimensions. If your mask is 2D ((H, W)), expand it to 3D first:
    # Expand 2D mask to match 3D color image
    mask_3d = np.expand_dims(mask, axis=-1)
    result = image.copy()
    result[~mask_3d] = 0
    
  • Handle Transparent Masks: If your mask is an RGBA image, extract the alpha channel or convert to grayscale before converting to a boolean mask.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:47:54