在OpenCV2中寻找最接近图像中心的轮廓。

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

我正在尝试使用openCV2从静态地图中自动划分教堂和大教堂的轮廓。

简而言之,我是在

  • 从静态地图上刮取建筑的坐标 本维基百科.
  • 使用Folium(一个Python库)创建一个以这些坐标为中心的地图。
  • 将地图保存为JPG图像。
  • 应用openCV2的 findContours 的方法来划分建筑物的轮廓。

我最初假设大教堂是几百米内最大的建筑,所以我按照面积对等高线进行了排序。这个PyImageSearch教程:

contours = sorted(contours, key = cv2.contourArea, reverse = True)[0:1]

在少数情况下,这种方法很有效,比如圣彼得大教堂。

enter image description here

然而,根据城市和所选的变焦级别,我经常会选择附近的建筑物,实际上比教堂更大。

enter image description here

我想选择最接近图像中心的轮廓。

一个选项是计算地图中所有轮廓的中心,然后确定最接近图像城市中心的点,但我想知道是否有一个更简单的解决方案。

python opencv contour
1个回答
2
投票

我使用了 cv2.moments(contour) 如图 本文 来获得每个轮廓的中心。然后您可以使用 distance.euclidian 来自 scipy.spatial 模块来计算每个轮廓到图像中心的距离。

示例图像。

enter image description here

代码:

    import cv2
    import numpy as np
    from scipy.spatial import distance
    
    
    sample_img = cv2.imread("sample_buildings.png")
    
    # convert to black and white color space
    sample_img_grey = cv2.cvtColor(sample_img, cv2.COLOR_BGR2GRAY)
    contours, hierarchy = cv2.findContours(sample_img_grey, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    #find center of image and draw it (blue circle)
    image_center = np.asarray(sample_img_grey.shape) / 2
    image_center = tuple(image_center.astype('int32'))
    cv2.circle(sample_img, image_center, 3, (255, 100, 0), 2)
    
    buildings = []
    for contour in contours:
        # find center of each contour
        M = cv2.moments(contour)
        center_X = int(M["m10"] / M["m00"])
        center_Y = int(M["m01"] / M["m00"])
        contour_center = (center_X, center_Y)
    
        # calculate distance to image_center
        distances_to_center = (distance.euclidean(image_center, contour_center))
    
        # save to a list of dictionaries
        buildings.append({'contour': contour, 'center': contour_center, 'distance_to_center': distances_to_center})
    
        # draw each contour (red)
        cv2.drawContours(sample_img, [contour], 0, (0, 50, 255), 2)
        M = cv2.moments(contour)
    
        # draw center of contour (green)
        cv2.circle(sample_img, contour_center, 3, (100, 255, 0), 2)
    
    # sort the buildings
    sorted_buildings = sorted(buildings, key=lambda i: i['distance_to_center'])
    
    # find contour of closest building to center and draw it (blue)
    center_building_contour = sorted_buildings[0]['contour']
    cv2.drawContours(sample_img, [center_building_contour], 0, (255, 0, 0), 2)
    
    cv2.imshow("Image", sample_img)
    cv2.waitKey(0)

结果图像:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.