python – 使用numpy.unravel_index

嗨,我有一个名为mi_reshaped的2×4数组.我使用argmax找出数组中最大元素的indeces.现在我想将这些indeces转换为x,y坐标.所以我使用了numpy.unravel_index.我收到此错误:

Traceback (most recent call last):
File "CAfeb.py", line 273, in <module>
analyzeCA('full', im)
File "CAfeb.py", line 80, in analyzeCA
bg_params = parameterSearch( im, [3, 2], roi, ew, hist_sz, w_data);
File "CAfeb.py", line 185, in parameterSearch
ix = np.unravel_index(max_ix, mi_reshaped.shape)#(mi.size)
File "/usr/lib/pymodules/python2.7/numpy/lib/index_tricks.py", line 64, in unravel_index
if x > _nx.prod(dims)-1 or x < 0:
ValueError: The truth value of an array with more than one element isambiguous.   
  a.any() or a.all()
mi_reshaped=mi.reshape(2,4)
max_ix = np.argmax(mi_reshaped, axis=1)
ix = np.unravel_index(max_ix, mi_reshaped.shape)#(mi.size)

谢谢

最佳答案 你应该跳过轴= 1.如果你执行numpy.argmax(数组),它将在flattened数组中查找max,然后你可以使用数组形状执行unravel_index来查找实际索引.传递轴时,numpy将为数组中的每个条目查找该轴的最大值.例如:

>>>data = numpy.array(range(8)).reshape(2, 4)
>>>data
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>>max_ix = numpy.argmax(data, axis=1)
>>>max_ix
array([3, 3])  
>>>numpy.unravel_index(max_ix, data.shape)
(array([0, 0]), array([3, 3]))

现在,如果你跳过轴:

>>>max_ix = numpy.argmax(data)
>>>max_ix
7
>>>numpy.unravel_index(max_ix, data.shape)
(1, 3)

现在发生的事情是你告诉numpy给你维度1的最大值索引,它找到索引[3,3]的最大值’3’和’7′.你的代码仍然不会出错,只是错误的最终结果.

点赞