Skip to main content
 首页 » 编程设计

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

2025年05月04日15Renyi-Fan

有没有一种快速有效的方法来找到 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为了这。这将返回对应于沿给定轴的最大值的元素的索引。

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