Numpy:如何用矢量化替换单值数组?

Numpy: How to replace array with single value with vectorization?

我将图像保存为形状 [Height, Width, 3] 的 numpy 数组,我想根据像素的颜色用另一个值替换每个像素,因此最终数组的形状将是 [Height, Weight] .

我的 for 循环解决方案有效,但速度很慢。如何使用 Numpy 向量化使其更高效?

image = cv2.imread("myimage.png")

result = np.zeros(shape=(image.shape[0], image.shape[1],))
for h in range(0, result.shape[0]):
        for w in range(0, result.shape[1]):
            result[h, w] = get_new_value(image[h, w])

这里是get_new_value函数:

def get_new_value(array: np.ndarray) -> int:
    mapping = {
        (0, 0, 0): 0,
        (0, 0, 255): 5,
        (0, 100, 200): 8,
        # ...
    }
    return mapping[tuple(array)]

您可以使用 np.select() 如下所示:


img=np.array(
[[[123 123 123]
  [130 130 130]]

 [[129 128 128]
  [162 162 162]]])

condlist = [img==[123,123,123], img==[130, 130, 130], img==[129, 129, 129], img==[162, 162, 162]]
choicelist = [0, 5, 8, 9]
img_replaced = np.select(condlist, choicelist)
final = img_replaced[:, :, 0]

print('img_replaced')
print(img_replaced)
print('final')
print(final)

condlist 是您的颜色值列表,choicelist 是替换列表。

np.select 然后 returns 三个通道,你只需要从中取出一个通道来给出数组 'final' 我相信这是你想要的格式

输出为:

img_replaced
[[[0 0 0]
  [5 5 5]]

 [[0 0 0]
  [9 9 9]]]
final
[[0 5]
 [0 9]]

所以您的示例的特定代码和显示的颜色映射将是:

image = cv2.imread("myimage.png")

condlist = [image==[0, 0, 0], image==[0, 0, 255], image==[0, 100, 200]]
choicelist = [0, 5, 8]
img_replaced = np.select(condlist, choicelist)
result = img_replaced[:, :, 0]