在numpy矩阵

时间:2016-03-20 17:43:07

标签: python arrays performance numpy python-imaging-library

是否有一种快速有效的方法来查找具有最高值的NxM Numpy数组的每一列中的行?

我目前正在通过Python中的嵌套循环执行此操作,这相对较慢:

from PIL import Image
import numpy as np
img = Image.open('sample.jpg').convert('L')
width, height = size = img.size
y = np.asarray(img.getdata(), dtype=np.float64).reshape((height, width))
max_rows = [0]*width
for col_i in xrange(y.shape[1]):
    max_vaue, max_row = max([(y[row_i][col_i], row_i) for row_i in xrange(y.shape[0])])
    max_rows[col_i] = max_row

对于640x480图像,这需要大约5秒钟。不是很大,但更复杂的图像操作,如模糊,完全在Numpy / PIL / C中实现需要0.01秒或更短时间。这是我试图在视频流上执行的操作,因此这是一个巨大的瓶颈。如果没有编写自己的C扩展,我如何加快速度?

1 个答案:

答案 0 :(得分:4)

您可能希望使用numpy.argmax。这将返回与给定轴上的最大值对应的元素的索引。

row_index = np.argmax(y, axis=0)

# Alternately
row_index = y.argmax(axis=0)

为了举例

data = np.random.rand(4,2)
# array([[ 0.09695379,  0.44602826],
#        [ 0.73614533,  0.19700072],
#        [ 0.87843682,  0.21188487],
#        [ 0.11389634,  0.51628872]])

row_index = data.argmax(axis=0)
# array([2, 3])
相关问题