OpenCV:计算从轮廓点到pygame对象的距离失败

问题描述 投票:0回答:1

我正在借助摄像机和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)

enter image description here

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

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

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

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

我在做什么错?距离功能正在运行,我已经通过仅计算到绿色圆圈的1个点的距离进行了手动测试。

以下是相关代码段:

     ...

     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
python opencv pygame
1个回答
0
投票

您的条件应该是:

if distanceList[-1] < minCoordinates:
© www.soinside.com 2019 - 2024. All rights reserved.