You need to enable JavaScript to run this app. 如何通过编程方式从bitmap位图生成对应mask遮罩
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程方式从bitmap位图生成对应mask遮罩

实现原理

你需要的遮罩效果本质是提取原图的非透明区域轮廓,将所有不透明度高于阈值的像素统一替换为纯色(可自定义颜色),透明区域保持原透明属性即可。

分场景实现方案

1. Android平台(Kotlin实现)

适用于安卓端Bitmap实时处理场景:

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color

fun generateMaskBitmap(source: Bitmap, maskColor: Int = Color.WHITE, alphaThreshold: Int = 128): Bitmap {
    // 创建和原图尺寸、格式一致的空Bitmap
    val mask = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
    // 批量读取所有像素提升性能
    val pixelArray = IntArray(source.width * source.height)
    source.getPixels(pixelArray, 0, source.width, 0, 0, source.width, source.height)
    
    for (i in pixelArray.indices) {
        val alpha = Color.alpha(pixelArray[i])
        pixelArray[i] = if (alpha > alphaThreshold) {
            maskColor
        } else {
            Color.TRANSPARENT
        }
    }
    // 批量写入处理后的像素
    mask.setPixels(pixelArray, 0, source.width, 0, 0, source.width, source.height)
    return mask
}

如果不需要保留透明度,直接生成纯黑白单通道遮罩,可将输出Bitmap配置改为ALPHA_8格式即可。

2. Python 批量处理(Pillow实现)

适用于本地图片批量生成遮罩的场景:

from PIL import Image

def generate_mask(source_img_path: str, output_path: str, mask_rgba: tuple = (255, 255, 255, 255), alpha_threshold: int = 128):
    with Image.open(source_img_path).convert("RGBA") as src:
        width, height = src.size
        mask_img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
        # 批量读取像素
        src_pixels = src.load()
        mask_pixels = mask_img.load()
        
        for x in range(width):
            for y in range(height):
                *_, alpha = src_pixels[x, y]
                if alpha > alpha_threshold:
                    mask_pixels[x, y] = mask_rgba
        mask_img.save(output_path)

如果需要生成单通道mask,可将输出图片格式改为L,非透明区域赋值为255,透明区域赋值为0即可。

可调参数说明

  • 透明度阈值alphaThreshold:默认设为128,可根据原图的半透明效果调整,值越高只有完全不透明的区域才会被计入遮罩,值越低半透明区域也会被纳入遮罩。
  • 遮罩颜色:可按需修改maskColor/mask_rgba参数,自定义遮罩的显示颜色。

内容的提问来源于stack exchange,提问作者Adil Raza Bangash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 10:24:10