(逻辑索引)在numpy数组

时间:2017-05-31 11:07:58

标签: python python-2.7 numpy indexing python-imaging-library

我试图通过逻辑索引访问值来取代我的png图像。之前它在python for循环中工作但我无法通过使用逻辑索引来完成它。 (for循环最多需要1分钟)

以numpy数组获取我的图像

img = Image.open('test.png')
matrix = numpy.array(img)

使用common 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 test.png

for循环看起来像什么(想要的结果) test_unpm.png

使用索引看起来如何 enter image description here

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题,这应该可以胜任:

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中找到最终结果。

答案 1 :(得分:1)

这是一种方法 -

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]

因此,更新的值将在matrix