如何将二值图像中的黑色区域替换为RGB绿色并保留白色区域?
解决方案:将二值图像黑色区域替换为RGB绿色
你的二值图像binary是布尔数组,其中True对应白色区域(灰度值大于Otsu阈值),False对应黑色区域。要实现颜色替换,我们需要基于这个掩码创建RGB格式图像,给不同区域填充对应颜色。
步骤说明
- 初始化与原图像尺寸一致的3通道RGB图像
- 利用二值掩码批量赋值:
- 白色区域(
binary == True)设为RGB白色(255,255,255)(若原图像是0-1浮点数格式则用(1,1,1)) - 黑色区域(
binary == False)设为RGB绿色(0,255,0)(对应0-1格式的(0,1,0))
- 白色区域(
- 显示或保存处理后的图像
完整整合代码
import cv2 import matplotlib.pyplot as plt import numpy as np from skimage.filters import threshold_otsu # 1. 读取图像(修正原代码中BURNABLE未定义问题,如需使用请先赋值) forest = plt.imread("island.png") # 示例:若BURNABLE是0-1浮点数,可定义为 BURNABLE = 0.6 # forest[:,:,1] = BURNABLE print(forest.shape) print("The image of the forest consists of %i pixels" % (forest.shape[0] * forest.shape[1])) plt.imshow(forest); plt.show() # 2. 转换为灰度图 grayed_forest = cv2.cvtColor(forest, cv2.COLOR_BGR2GRAY) plt.imshow(grayed_forest, cmap = 'gray') plt.show() print(grayed_forest.shape) # 3. 转换为二值图像 thresh = threshold_otsu(grayed_forest) print(thresh) binary = grayed_forest > thresh plt.imshow(binary, cmap='gray') plt.show() # 4. 替换黑色区域为绿色,保留白色区域 # 针对0-255整数型图像的处理 rgb_image = np.zeros((forest.shape[0], forest.shape[1], 3), dtype=np.uint8) rgb_image[:] = (0, 255, 0) # 先整体设为绿色 rgb_image[binary] = (255, 255, 255) # 白色区域覆盖为白色 # 若原图像是0-1浮点数格式,替换为以下代码: # rgb_image = np.zeros((forest.shape[0], forest.shape[1], 3), dtype=np.float32) # rgb_image[:] = (0, 1, 0) # rgb_image[binary] = (1, 1, 1) # 显示最终结果 plt.imshow(rgb_image) plt.show()
关键细节提示
- 注意图像数据类型:
plt.imread读取PNG多为0-1浮点数,JPG则是0-255整数,需对应调整颜色值 - 布尔掩码
binary可直接用于索引像素,实现批量赋值,效率远高于循环遍历 - 若原图像用
cv2.imread读取,通道顺序是BGR,但我们新建的是RGB图像,无需额外转换
内容的提问来源于stack exchange,提问作者RadAstronomer
相关产品推荐
相关产品推荐

