gpt4 book ai didi

python - 使用 numpy.unravel_index

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:27 25 4
gpt4 key购买 nike

您好,我有一个名为 mi_reshaped 的 2x4 数组。我使用 argmax 找出数组中最大元素的索引。现在我想将这些索引转换为 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)

谢谢

最佳答案

为此您应该跳过 axis=1。如果你执行 numpy.argmax(array),它会在展平的数组中寻找最大值,然后你可以使用数组形状执行 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”。您的代码仍然不会出错,只是错误的最终结果。

关于python - 使用 numpy.unravel_index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9514438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com