如何进行numpy数组颜色相似度转换

时间:2019-03-04 02:31:08

标签: python numpy

如果a具有一个numpy数组且形状为(1920,1080,3),如何将类似于绿色的所有像素更改为恰好为(0,255,0)?

2 个答案:

答案 0 :(得分:0)

coords = []
for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        if matrix[i][j][0] == 0 and matrix[i][j][1] == 255 and matrix[i][j][2] == 0:
            coords.append((i, j))

我认为这不是很有效,但是可以。

答案 1 :(得分:0)

“关闭”的含义非常重要。如果来自完美绿色的像素的L_2范数小于50,则我认为像素“接近”绿色。使用这样的标准,您可以使用矢量化方法高效地进行替换。在这种情况下,请使用布尔掩码,该布尔掩码在所有像素接近的地方都是True,在没有像素的所有地方都是False

import numpy as np 

# first make a test image

nx = ny = 300 # dimensions of image
green = np.array([0,255,0]) # perfect green 
im = np.random.randint(0,255,size=(nx,ny,3)) # make a fake image 


# now we make a boolean mask with shape (nx, ny) 
# it is true everywhere the L_2 distance between a pixel in im and a
# perfect green is less than 50. Here's where you need to confine what
# you mean by 'close'

mask = np.sum((im-green)**2,axis=-1) < 50**2 # mask with shape (nx, ny)
im[mask] = green # reassign all close pixels to green