You need to enable JavaScript to run this app. Numpy图像数组指定颜色替换为1其余为0的语义分割编码实现
优惠活动
大模型
产品
解决方案
定价
更多

Numpy图像数组指定颜色替换为1其余为0的语义分割编码实现

语义分割RGB颜色匹配掩码生成实现方案

我们可以通过numpy的广播布尔运算实现需求,该方案天然兼容单张(H, W, 3)和批量(N, H, W, 3)格式的输入,不需要额外调整逻辑。

实现步骤

  • 导入numpy依赖
  • 定义目标匹配RGB值
  • 对输入数组的最后一个通道(RGB通道)做全值匹配判断
  • 将布尔结果转为uint8类型的0/1值,得到最终掩码

代码示例

import numpy as np

def rgb_to_mask(input_array, target_rgb):
    # 最后一个维度全匹配时返回True,否则False
    match_mask = (input_array == target_rgb).all(axis=-1)
    # 布尔值转uint8的0/1,符合输出要求
    return match_mask.astype(np.uint8)

效果验证

单样本测试(对应你给出的小例子)

# 输入测试数组
test_input = np.array([[20,20,20], [30,30,30], [40,40,40]])
target = [20,20,20]
print(rgb_to_mask(test_input, target))
# 输出为 [1 0 0],和预期一致

单张图像测试

# 生成模拟的单张128*256 RGB图像
single_img = np.random.randint(0, 255, size=(128, 256, 3), dtype=np.uint8)
target_color = [255, 0, 0] # 示例匹配红色
mask = rgb_to_mask(single_img, target_color)
print(mask.shape) # 输出为 (128, 256),符合预期

批量图像测试

# 生成模拟的16张批量图像
batch_imgs = np.random.randint(0, 255, size=(16, 128, 256, 3), dtype=np.uint8)
target_color = [255, 0, 0]
batch_mask = rgb_to_mask(batch_imgs, target_color)
print(batch_mask.shape) # 输出为 (16, 128, 256),批量中每张图都生成了对应掩码

注意事项

  • 请确保输入数组和target_rgb的数值类型一致,避免因类型差异导致匹配失败,比如输入是uint8类型时,target_rgb也用0-255的整数即可
  • 如果需要同时匹配多个目标颜色,可以将target_rgb修改为形状为(K, 3)的数组(K为目标颜色数量),通过np.isin或者广播叠加匹配结果即可扩展功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:57:03