【问题标题】:OpenCV: calculating distance from contour points to an pygame object failsOpenCV:计算从轮廓点到 pygame 对象的距离失败
【发布时间】:2020-07-17 19:53:03
【问题描述】:

在相机和 OpenCV 的帮助下,我正在接收移动物体的实时轮廓。 它在 pygame 窗口中运行:

           # Find contours on thresholded image
           nada, contours, nada = cv2.findContours(frame5.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

当我遍历所有这些轮廓点时,我可以通过为每个轮廓点绘制白色小圆圈来将它们可视化,如下所示:

           for i in contours:
              for j in range(len(i)):
                 coordinates = i[j][0]
                 pygame.draw.circle(screen, WHITE, coordinates, 1, 0)

白色的小圆圈是轮廓点。它们的坐标显示正确(我手动检查过)。

绿色大圆圈的位置固定在 (960, 540)。

现在我想找到离绿色大圆圈最近的白色轮廓点并将其显示为蓝色大圆圈。

为此,我正在计算每个轮廓点到绿色圆圈的距离,距离最小的那个显示为一个蓝色的大圆圈。但是,正如您在图片中看到的那样,蓝色圆圈离绿色圆圈很远。

我做错了什么?距离功能正在工作,我通过仅计算 1 点到绿色圆圈的距离来手动测试它。

这里是相关代码sn-p:

     ...

     while True:

        ...

        screen.fill(BLACK)

        # Find contours on thresholded image
        nada, contours, nada = cv2.findContours(frame5.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        if len(contours) != 0:
            distanceList = []

            for i in contours:
                for j in range(len(i)):
                    coordinates = i[j][0]

                    # rigidbody.x and .y represents green circle's coordinates
                    distanceList.append(math.sqrt((rigidbody.x - coordinates[0]) ** 2 + (rigidbody.y - coordinates[1]) ** 2))
                    minDistance = distanceList[0]

                    # Find smallest distance of all contour points
                    if distanceList[j] < minDistance:
                        minCoordinates = coordinates

            for i in contours:
                for j in range(len(i)):
                    coordinates = i[j][0]
                    pygame.draw.circle(screen, WHITE, coordinates, 1, 0) # Render white contour points
                    pygame.draw.circle(screen, BLUE, minCoordinates, 50, 0)  # Render closest contour point to game object

编辑

我意识到距离的最小化器并没有最小化:

                # Find smallest distance of all contour points
                if distanceList[j] < minDistance:
                    print(frame)
                    print(distanceList[j])
                    minCoordinates = coordinates

所以对于第 106 帧,值是递增和递减的。但它应该只会减少。

Frame: 106
Distance:365.6364314452268

Frame: 106
Distance: 357.816992329878

Frame: 106
Distance: 359.133679846377

【问题讨论】:

    标签: python opencv pygame


    【解决方案1】:

    您不必跟踪所有距离来找到最小距离,您可以只使用当前/最后一个距离。

    在循环外用float('inf') 初始化minDistance

    然后使用这个条件:

    if distanceList[-1] < minDistance:
       minDistance = distanceList[-1]
       minCoordinates = coordinates
    

    【讨论】:

    • 不,因为坐标是坐标,距离是数字。但是,是的,我明白了你的观点。我修复了它,但仍然有同样的错误(见上面的编辑)
    • 我的错。我以为是minDistance
    • 编辑了我的答案。
    • 如果您的意思是获得无穷大的部分,那么也许。除此之外,我不得不说它是算法 101。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多