【问题标题】:Numpy: How to replace array with single value with vectorization?Numpy:如何用向量化替换数组?
【发布时间】:2020-07-24 09:52:32
【问题描述】:

我有一个图像保存为形状为[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)]

【问题讨论】:

  • 你能告诉我们你的get_new_value函数吗?
  • 映射是否包含 256^3 个值(对于所有像素)?您可以访问和编辑 get_new_value 函数吗?
  • 是的,我可以编辑这个函数。该映射包含每个可能的像素值的值。

标签: python numpy vectorization


【解决方案1】:

你可以使用 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 然后返回三个通道,您只需要从中获取一个通道即可为数组提供“最终”格式,我相信这是您想要的格式

输出是:

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]

【讨论】:

  • result = img_replaced[:, :, 0] 这一行在某些情况下会产生错误的结果。将其替换为result = img_replaced[:, :].max(axis=2)
猜你喜欢
  • 2018-10-30
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多