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

Python中是否有函数可将二值图像的白色像素填充为红色?

二值图白色像素替换为红色的实现方案

以下提供Python生态下两种最常用的实现方式,你可以根据现有依赖选择:

方案1:基于OpenCV实现

首先安装依赖:
pip install opencv-python numpy
完整代码:

import cv2
import numpy as np

# 读取二值图像,保留原通道属性
binary_img = cv2.imread("你的输入图像路径.png", cv2.IMREAD_UNCHANGED)
# 单通道转三通道BGR格式,方便赋彩色值
color_img = cv2.cvtColor(binary_img, cv2.COLOR_GRAY2BGR)
# 匹配所有白色像素(二值图默认白色值为255)的位置
white_mask = binary_img == 255
# 将匹配位置替换为红色,OpenCV通道顺序为BGR,红色对应(0,0,255)
color_img[white_mask] = (0, 0, 255)
# 保存结果
cv2.imwrite("输出图像路径.png", color_img)

方案2:基于Pillow实现

首先安装依赖:
pip install pillow numpy
完整代码:

from PIL import Image
import numpy as np

# 读取图像并转单通道灰度格式,确保输入为标准二值结构
binary_img = Image.open("你的输入图像路径.png").convert("L")
binary_arr = np.array(binary_img)
# 初始化三通道RGB数组
rgb_arr = np.zeros((binary_arr.shape[0], binary_arr.shape[1], 3), dtype=np.uint8)
# 白色像素位置填充红色,Pillow通道顺序为RGB,红色对应(255,0,0)
rgb_arr[binary_arr == 255] = [255, 0, 0]
# 非白色像素默认保留黑色,如有需要可以修改此处的赋值
rgb_arr[binary_arr != 255] = [0, 0, 0]
# 导出结果
res_img = Image.fromarray(rgb_arr)
res_img.save("输出图像路径.png")

注意事项

  • 如果你的二值图白色像素不是标准的255,修改代码中==255的判断值即可
  • 两种方案均采用numpy广播运算,无需手动遍历像素,大尺寸图像处理效率也足够高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:01