简体   繁体   English

Numpy:如何用向量化替换数组?

[英]Numpy: How to replace array with single value with vectorization?

I have an image saved as numpy array of shape [Height, Width, 3] and I want to replace every pixel with another value based on the color of pixel, so the final array will have a shape [Height, Weight] .我有一个图像保存为 numpy 形状[Height, Width, 3]数组,我想用基于像素颜色的另一个值替换每个像素,因此最终数组将具有形状[Height, Weight]

My solution with for loop works but it's pretty slow.我的 for 循环解决方案有效,但速度很慢。 How can I use Numpy vectorization to make it more efficient?如何使用 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])

Here is get_new_value function:这是 get_new_value function:

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)]

you can use np.select() as shown below:您可以使用 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 is your list of colour values and choicelist is the list of replacements. condlist 是您的颜色值列表,choicelist 是替换列表。

np.select then returns three channels and you just need to take one channel from that to give the array 'final' which is the format you want I believe np.select 然后返回三个通道,您只需要从中获取一个通道即可为数组“最终”提供我相信的格式

output is: output 是:

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

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

so code specific to your example and shown colour mappings would be:因此特定于您的示例的代码和显示的颜色映射将是:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM