Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在图像数组中查找颜色并用值填充2D数组_Python_Image_Numpy_Colors - Fatal编程技术网

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

Python在图像数组中查找颜色并用值填充2D数组,python,image,numpy,colors,Python,Image,Numpy,Colors,我有一个带有颜色分割的图像,我想从BGR颜色列表中找到具有颜色的像素。从这些像素索引中,我想用一些任意值填充2D数组。我已经完成了这项工作,但进展非常缓慢: #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 an

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

#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循环中替换它们。这里的颜色+1000是您引用的任意值 对

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

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

此外,如果您使用的是大型阵列(图像),并且拥有NVIDIA图形卡,请查看cupy而不是numpy。它有相同的符号,但使用图形卡大大增强了基于矩阵的数学。性能可能会快几个数量级。这不起作用,因为我的输出与图像的形状不同。图像有3个维度:w、h和通道。我的输出只是一个2D数组。