繁体   English   中英

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

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

我有一个带有颜色分割的图像,我想从 BGR 颜色列表中找到具有颜色的像素。 从这些像素索引中,我想用一些任意值填充一个二维数组。 我已经完成了这个,但它非常慢:

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

必须有一种更快的方法来做到这一点,可能使用 np.where 但我就是想不通。

我认为这可以按照以下示例中的执行来完成。 下面是一个可以根据您的需要进行扩展的简化示例。

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

我们简单地遍历您想要在 BGR 列表中查找的颜色值,并在 for 循环中替换它们。 这里 color+1000 是您引用的任意值。

对于您的情况,它将显示如下:

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