如何更改numpy数组中的像素值

leo*_*mme 2 python numpy python-2.7

我有一个大的RGB图像作为一个numpy数组,我想将所有具有R = 0,G = 0,B = 0的像素设置为R = 255,G = 0,B = 0。最快的方法是什么?我试过了:

for pix in result:
    if np.all(np.logical_and(pix[0]==pix[1],pix[2]==0,pix[2]==pix[1])):
        pix [0] = 255
Run Code Online (Sandbox Code Playgroud)

但是以这种方式,我没有一个像素。有没有不重复索引的类似方法?

Mag*_*n88 5

这是向量化的解决方案。您的图像基本上是一个3 x彩色的w x h阵列。我们可以利用不容易掌握但功能强大的广播规则。

基本上,我们将整个数组与您要查找的值的3向量进行比较。根据广播规则,Numpy随后会将每个像素与该三个向量进行比较,并告诉您是否匹配(因此在这种特定情况下,红色,绿色和蓝色是否匹配)。您最终将得到一个与图像大小相同的对错的布尔数组。

现在我们只想找到所有三种颜色都匹配的像素。为此,我们使用“ all”方法,如果数组的所有值均为true,则为true。如果将其应用于特定轴(在本例中为颜色轴),则无论所有颜色都匹配,我们都会得到一个w by h数组,该数组为true。

现在,我们可以将此2D布尔蒙版应用回原始的w by h by 3数组,并获得与我们的颜色匹配的像素。现在,我们可以通过广播重新分配他们了。

这是示例代码

import numpy as np

#create a 2x2x3 image with ones
img = np.ones( (2,2,3) )

#make the off diagonal pixels into zeros
img[0,1] = [0,0,0]
img[1,0] = [0,0,0]

#find the only zeros pixels with the mask 
#(of course any other color combination would work just as well)
#... and apply "all" along the color axis
mask = (img == [0.,0.,0.]).all(axis=2)

#apply the mask to overwrite the pixels
img[ mask ] = [255,0,0]
Run Code Online (Sandbox Code Playgroud)