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

如何使用Python的numpy where函数批量修改图像RGB值

批量替换图像中指定RGB值的方法

直接用numpy的布尔索引就能实现高效批量替换,完整代码如下:

from PIL import Image
import numpy as np

target_file = r'D:\rgb_test\C\test.tga'
img = Image.open(target_file)
basePixel = np.array(img)

old_rgb_value = (255, 0, 0)
new_rgb_value = (57, 57, 57)

# 生成匹配旧RGB值的布尔掩码
mask = np.all(basePixel == old_rgb_value, axis=-1)
# 批量替换匹配的像素
basePixel[mask] = new_rgb_value

# 可选:保存修改后的图像
img_new = Image.fromarray(basePixel)
img_new.save(r'D:\rgb_test\C\test_modified.tga')

关键逻辑说明

  • np.all(basePixel == old_rgb_value, axis=-1):沿着图像的RGB通道维度(axis=-1),逐个校验每个像素的三个通道值是否完全匹配旧RGB值,生成与图像尺寸一致的布尔数组(匹配位置为True,其余为False)
  • basePixel[mask] = new_rgb_value:借助numpy布尔索引特性,直接将所有掩码为True的像素批量赋值为新RGB值,效率远高于循环遍历修改

内容的提问来源于stack exchange,提问作者J.Shim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:34:51