首页 > 解决方案 > Numpy:有效地将满足条件的所有像​​素设置为黑色

问题描述

我需要将满足某些条件的所有像​​素更改为黑色。我的快速解决方案是迭代每个像素。我的应用程序对性能很敏感,并且比要求的要慢。它循环的图像尺寸非常小,从大约 25x25 到 50x50 不等。

我已经提供了一个我正在做的例子。如果图像加载或宽度/高度部分有任何错误,我们深表歉意。

image = cv2.imread("image.png")
width, height = image.shape

for x in range(width):
    for y in range(height):
        blue = image[x, y, 0]
        green = image[x, y, 1]
        red = image[x, y, 2]

        if (abs(green - blue) > 20 and green > 30) or abs(red - green) < 40:
            output[x, y] = [0, 0, 0]

标签: pythonnumpy

解决方案


使用矢量化操作和掩码 -

import numpy as np

# Convert to int datatype, as we want to avoid overflow later on
image_int = image.astype(int)

# Split up the channels
B,G,R = image_int.transpose(2,0,1)
# Or image_int[...,0],image_int[...,1],image_int[...,2]

# Use numpy.abs and 2D sliced data to get 2D mask
mask = mask = ((np.abs(G - B) > 20) & (G>30)) | (np.abs(R - G) < 40)

# Use the mask to assign zeros into o/p with boolean-indexing
output[mask] = [0,0,0]

推荐阅读