具有多个元素的数组的真值不明确。按索引从列表中删除时,请使用a.any()或a.all()

2024-09-30 06:15:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着取最大的n个轮廓,去掉其他的。 但我在某些帧中得到了这个异常,而在其他帧中却没有! 尝试从列表中删除轮廓时发生异常

Traceback (most recent call last):
File "/Users/TheMaestro/Desktop/Max Planck/FishTracking/FishTracker/general_tests.py", line 93, in <module>
contours_chest = ImageProcessor.get_bigest_n_contours(contours_chest, 3)
File "/Users/TheMaestro/Desktop/Max Planck/Fish Tracking/FishTracker/Controllers/ImageProcessor.py", line 319, in get_bigest_n_contours
contours.remove(contours[i])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这是我的代码:

电话:

^{pr2}$

功能:

def get_biggest_n_contours(contours, n):
    contours = sorted(contours, key=get_area, reverse=True)

    contours_count = len(contours)

    if contours_count > n:
        for i in range(n,contours_count):
            contours.remove(contours[i])
            i -= 1

    return contours

Data information 我检查了前面的答案,但我不知道在哪里使用a.any或a.all,也不知道为什么要在我的案例中使用它们! 我删除了使用索引,所以我看不到一个导致歧义的比较!在

谢谢你


Tags: inpygetcountlineusersmaxfile
2条回答

我不完全确定contours的形状,但我怀疑在调用sorted之后,您创建了一个由numpy数组组成的python列表。在

在这行contours.remove(contours[i])中,您尝试从numpy数组列表中删除一个元素。list.remove方法对list中的所有元素进行线性搜索,并将它们与要删除的元素进行比较。因此,您将在remove方法中比较numpy数组和numpy数组,并在这个比较的布尔值上分支,这个值是不明确的。在

不必使用remove(实际上只有在不知道要删除的元素的索引时才会使用它),您可以pop该索引处的元素。在

但在你的情况下似乎有更好的选择。如果我观察正确,您希望在contours中找到n最大的条目。在python中,当数据被排序时,这是一个简单的任务(您已经做到了)。因此,可以在对数组进行排序后对其进行切片:

def get_biggest_n_contours(contours, n):
    contours = sorted(contours, key=get_area, reverse=True)

    return contours[:n]

切片会帮你做所有的工作 1{如果所有元素都小于^则返回它们 2如果确实存在n元素,则返回所有元素 三。如果有更多,只需返回第一个n元素

通常不应在迭代列表时将其从列表中移除,但这是不对的:

for i in range(n,contours_count):
    contours.remove(contours[i])
    i -= 1

{{{cd2>中的下一个迭代{elmnt}将不具有实数效果。既然您想要第一个n轮廓,只需执行以下操作:

^{pr2}$

相关问题 更多 >

    热门问题