简体   繁体   English

Python在图像数组中查找颜色并用值填充二维数组

[英]Python find colors in image array and fill 2D array with value

I have an image with color segmentations and I want to find the pixels that have a color from a list of BGR colors.我有一个带有颜色分割的图像,我想从 BGR 颜色列表中找到具有颜色的像素。 From those pixel indexes I want to fill a 2D array with some arbitrary value.从这些像素索引中,我想用一些任意值填充一个二维数组。 I've accomplished this but it is terribly slow:我已经完成了这个,但它非常慢:

#load image with color segmentations
img = cv2.imread(segmented_img_path)
#create empty output array
output = np.zeros((img.shape[0], img.shape[1]))
#iterate over image and find colors
for i, row in enumerate(img):
    for j, bgr in enumerate(row):
        if np.any(np.all(np.isin(np.array(color_list),bgr,True),axis=1)):
            output[i,j] = float(some_value)

There's got to be a faster way of doing this, probably using np.where but I just can't figure it out.必须有一种更快的方法来做到这一点,可能使用 np.where 但我就是想不通。

I think this can be done as performed in the following example.我认为这可以按照以下示例中的执行来完成。 Below is a simplified example that can be scaled to your needs.下面是一个可以根据您的需要进行扩展的简化示例。

m = np.array(([1,2,3], [4,5,6], [1,2,3]))
d = np.zeros((np.shape(m)))
BGR = [1,3]
for color in BGR:
   d[m==color] = color+1000

We simply loop through the color values you want to find in a BGR list and replace them in the for loop.我们简单地遍历您想要在 BGR 列表中查找的颜色值,并在 for 循环中替换它们。 Here color+1000 is an arbitrary value you refer to.这里 color+1000 是您引用的任意值。

For your case it would appear as follows:对于您的情况,它将显示如下:

img = cv2.imread(segmented_img_path)
output = np.zeros((img.shape))
for bgr in BGR:
   output[img==bgr] = float(some_value)

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

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