在Python中标准化多边形坐标

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

我正在尝试标准化坐标两个多边形。然而,在标准化之后,它们只是相互重叠,这是不应该发生的。 这是我尝试过的。

import geopandas as gpd
from shapely.affinity import scale, translate
from shapely.geometry import Polygon

def normalize_polygon(polygon_shapefile, output_shapefile):
    """
    Normalizes the coordinates of the polygons in a shapefile to fit within a 0 to 1 range.

    :param polygon_shapefile: Path to the input polygon shapefile.
    :param output_shapefile: Path for the output shapefile with the normalized polygons.
    """
    
    polygon_gdf = gpd.read_file(polygon_shapefile)
    length_polygon = polygon_gdf[polygon_gdf.columns[0]].count()
    normalized_geometries = []
    for i in range(length_polygon):
        geometry = polygon_gdf.loc[i].geometry
        
        # Assume 'geometry' is your initial Polygon object
        bounds = geometry.bounds  # Returns a tuple (minx, miny, maxx, maxy)

        # Calculate the range for x and y
        x_range = bounds[2] - bounds[0]  # maxx - minx
        y_range = bounds[3] - bounds[1]  # maxy - miny

        # Normalize coordinates to the range [0, 1]
        normalized_coords = [((x - bounds[0]) / x_range, (y - bounds[1]) / y_range) for x, y in geometry.exterior.coords]

        # Create a new polygon with these normalized coordinates
        normalized_polygon = Polygon(normalized_coords)
        normalized_geometries.append(normalized_polygon)
    
    polygon_gdf.geometry = normalized_geometries
    print(polygon_gdf)
    polygon_gdf.to_file(output_shapefile)
    
input_log = "input.shp"
output_log = "output.shp"

normalize_polygon(input_log, output_log)

Before normalization After normalization

Similar to this

python polygon geopandas
1个回答
0
投票

与您之前的问题有点相似,您相对于每个单个几何体(i.e Polygon

)的
bounds而不是整个
total_bounds
进行变换。一个快速解决方法是删除
bounds = geometry.bounds
并将
bounds = polygon_gdf.total_bounds
放在循环之前 :

enter image description here

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