在轮廓之间画线(OpenCv/Python)

时间:2021-02-15 13:30:18

标签: opencv optimization opencv-python opencv-drawcontour

我正在尝试存档,在某些输入图像(请参阅下面的第二张图片)中根据覆盖区域(请参阅下面的第一张图片)在图像的轮廓之间绘制一条线。对于此操作,我正在执行以下操作:

  1. 在第一张图片中找到轮廓。
  2. 在第二张图片中找到轮廓。
  3. 对于第一张图像中的每个轮廓区域,与第二张图像中的所有轮廓(点)进行比较,并检查它们是否在第一张图像的轮廓内。如果它在轮廓区域内,将 x、y 坐标附加到列表中。
  4. 找到列表中每个项目最近的 2 点并画线。

我的问题是,有没有更好的方法来做这个操作或者我如何优化这个问题?

import cv2
from scipy.spatial import distance

delta = 2


def create_final():

    # Read images as grayscale
    cover = cv2.imread('cover.png', cv2.IMREAD_GRAYSCALE)
    layer = cv2.imread('1.png', cv2.IMREAD_GRAYSCALE)

    # Find Counters in Cover image
    coverContours = cv2.findContours(
        cover, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    coverContours = coverContours[0] if len(
        coverContours) == 2 else coverContours[1]

    # Find contours in layer image
    pointsContours = cv2.findContours(
        layer, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    pointsContours = pointsContours[0] if len(
        pointsContours) == 2 else pointsContours[1]

    for coverContour in coverContours:
        try:
            # Point_list x,y coordinates for every points in Cover area
            point_list = []

            for pointsContour in pointsContours:
                # Check this point inside of Cover Contour
                ((x, y), r) = cv2.minEnclosingCircle(pointsContour)

                if (cv2.pointPolygonTest(coverContour, (int(x), int(y)), False)) == 1:
                    # If inside of contour append to list
                    point_list.append((int(x), int(y)))

            # we find the points inside of cover area.
            for point in point_list:
                # Copy point_list to temp list
                temp = point_list.copy()

                # Remove point from temp list otherwise closest node will be itself.
                temp.remove(point)
                # Delta means connection number for one point.
                for x in range(0, delta):
                    # Find the closest point
                    end_point = __closest_node(point, temp)
                    # Remove closest point from list.
                    temp.remove(end_point)
                    # Draw line from one point to closest one.
                    cv2.line(layer, point, end_point,
                             255, 5)
        except:
            print('')

    cv2.imwrite('final.png', layer)


def __closest_node(node, nodes):
    if len(nodes) == 0:
        return node
    else:
        closest_index = distance.cdist([node], nodes).argmin()
    return nodes[closest_index]


create_final()


 

Cover Image Input Image Final Image

0 个答案:

没有答案