在numpy矩阵中查找最大列值的行索引

Finding row index of max column values in a numpy matrix

有没有一种快速有效的方法来找到 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 扩展之外,我该如何加快速度?

您将要为此使用 numpy.argmax。这将 return 对应于给定轴上最大值的元素的索引。

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])