Python (逻辑索引)为numpy数组中的RGBA值执行公式

Python (逻辑索引)为numpy数组中的RGBA值执行公式,python,python-2.7,numpy,indexing,python-imaging-library,Python,Python 2.7,Numpy,Indexing,Python Imaging Library,我试图通过逻辑索引访问值来增加我的png图像。以前在PythonforLoop中工作过,但我无法通过使用逻辑索引来正确完成。(for循环最多需要1分钟) 在numpy阵列中获取我的图像 img = Image.open('test.png') matrix = numpy.array(img) 使用公共for循环更改值 for line in matrix: for v in line: if v[3]: v[0] = (255 * v[0] + (v

我试图通过逻辑索引访问值来增加我的png图像。以前在PythonforLoop中工作过,但我无法通过使用逻辑索引来正确完成。(for循环最多需要1分钟)

在numpy阵列中获取我的图像

img = Image.open('test.png')
matrix = numpy.array(img)
使用公共for循环更改值

for line in matrix:
   for v in line:
       if v[3]:
           v[0] = (255 * v[0] + (v[3] / 2)) / v[3]
           v[1] = (255 * v[1] + (v[3] / 2)) / v[3]
           v[2] = (255 * v[2] + (v[3] / 2)) / v[3]
使用逻辑索引,结果是这样的

height, width, depth = matrix.shape
r = matrix[0:height, 0:width//4, 0:1]
g = matrix[0:height, 0:width//4, 1:2]
b = matrix[0:height, 0:width//4, 2:3]
a = matrix[0:height, 0:width//4, 3:4]

matrix[0:height, 0:width//4, 0:1] = (255 * r + (a / 2)) / a
matrix[0:height, 0:width//4, 1:2] = (255 * g + (a / 2)) / a
matrix[0:height, 0:width//4, 2:3] = (255 * b + (a / 2)) / a
如何正确更改所需的值? 如果有比使用逻辑索引更好的方法,请告诉我

编辑:添加示例图像

test.png

for循环的外观(期望结果)

使用索引是什么样子的

如果我正确理解您的问题,这应该可以完成以下工作:

r = matrix[:,:,0]
g = matrix[:,:,1]
b = matrix[:,:,2]
a = matrix[:,:,3]

r[a>0] = ((255*r + (a/2))/a)[a>0]
g[a>0] = ((255*g + (a/2))/a)[a>0]
b[a>0] = ((255*b + (a/2))/a)[a>0]
编辑

这一定是因为矩阵的
dtype
。如果您首先将矩阵更改为
float
值,它应该可以工作:

matrix2 = matrix.astype(np.float)

r = matrix2[:,:,0]
g = matrix2[:,:,1]
b = matrix2[:,:,2]
a = matrix2[:,:,3]

r[a>0] = ((255*r + (a/2))/a)[a>0]
g[a>0] = ((255*g + (a/2))/a)[a>0]
b[a>0] = ((255*b + (a/2))/a)[a>0]

matrix_out = matrix2.astype(np.uint8)
最后的结果可以在
矩阵中找到

这里有一种方法-

matrix_out = matrix.astype(float)
vals = (255 * matrix_out[...,:3] + matrix_out[...,[3]]/2)/matrix_out[...,[3]]
mask = matrix[...,3]!=0
matrix[mask,:3] = vals[mask]

因此,更新后的值将在
矩阵中

是那些循环的值,并且使用逻辑索引。有基础的人应该达到同样的目的吗?对于后者,您有
0:width//4
,这会造成混乱。为什么您只索引到
width//4
?在
for
循环中,您似乎没有这样做。@ThomasKühn获得4个值(RGBA)。它用错了吗?你把深度作为单独的索引。
matrix.shape
是什么样子的?这些是matrix.shape(24803508,4)的值。使用您的代码,图像最终是完全透明的。与“矩阵”相乘也包括alpha值,但只有rgb需要更改。现在刚刚尝试过。它给我的结果和我使用索引的方法一样。请参阅我刚刚添加的图像,以了解我试图实现的目标。与for循环和索引的值的差异如下:for循环[102 102 255]索引[0 0 255]@SHooDK,如其他帖子所述,似乎是dtype导致了问题。再次查看编辑。谢谢。数据类型似乎是个问题。将“float”更改为“np.float”,并将其速度提高了几毫秒。您的代码使用索引提供了与当前代码相同的结果,但简化了。查看我刚才添加的示例图像。也许这有助于了解我想要实现的目标。