我有一个Numpy数组中的图像。
我想将特定颜色替换为黑色,其他所有颜色替换为白色。
循环太慢,我的numpy条件不起作用。
所有匹配数组--[121,112,131]的像素必须完全替换为另一个数组--[0,0,0]
所有其他像素--->[255, 255, 255]
结果出现了忽略的像素,它们匹配第一个通道[True, False, False]
抱歉拼写错误,希望我的代码更易于理解。
我的示例结果:
import numpy as np
from scipy import misc
file = misc.face()
img = np.array(file)
target_color = [121, 112, 131]
true_color = [0, 0, 0]
false_color = [255, 255, 255]
true_mask = np.all(img == target_color, axis=2)
false_mask = np.all(img != target_color, axis=2)
img[true_mask] = true_color
img[false_mask] = false_color
print(img)
输出:
array([[[ 0, 0, 0],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
...,
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[121, 157, 96],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8)
问题:
当第一通道等于目标颜色时,会留下像素。
Target Pixel: [121, 112, 131]
Overseen Pixel: [121, 157, 96]
misc.face()
已经返回一个数组了。 - Mad Physicist