I'm looking for a solution in PyQGIS to create a cut line at the midpoint of another line that connects two points within a polygon. The objective is to cut the polygon into two parts.
In fact, this would be the alternative solution to the script below used to generate subdivisions in polygons with more than 2 points on it (based on cluster points and Voronoi). My problem is when I have two points inside one of these polygons.
The code was adapted from this link.
def split_polygon(poligonfeatures, numberofpoints, numberofparts):
# Random points inside polygons
alg_process = 'RandomPointsInsidePolygons'
alg_params = {
'INPUT': poligonfeatures,
'MIN_DISTANCE': None,
'STRATEGY': 0,
'VALUE': numberofpoints,
'OUTPUT': 'TEMPORARY_OUTPUT'
}
outputs[alg_process] = processing.run('qgis:randompointsinsidepolygons', alg_params)
# K-means clustering
alg_process = 'KmeansClustering'
alg_params = {
'CLUSTERS': numberofparts,
'FIELD_NAME': 'CLUSTER_ID',
'INPUT': outputs['RandomPointsInsidePolygons']['OUTPUT'],
'OUTPUT': 'TEMPORARY_OUTPUT'
}
outputs[alg_process] = processing.run('native:kmeansclustering', alg_params)
# Concave hull (k-nearest neighbor)
alg_process = 'ConcaveHullKnearestNeighbor'
alg_params = {
'FIELD': 'CLUSTER_ID',
'INPUT': outputs['KmeansClustering']['OUTPUT'],
'KNEIGHBORS': 3,
'OUTPUT': 'TEMPORARY_OUTPUT'
}
outputs[alg_process] = processing.run('qgis:knearestconcavehull', alg_params)
# Centroids
alg_process = 'Centroids'
alg_params = {
'ALL_PARTS': False,
'INPUT': outputs['ConcaveHullKnearestNeighbor']['OUTPUT'],
'OUTPUT': 'TEMPORARY_OUTPUT'
}
outputs[alg_process] = processing.run('native:centroids', alg_params)
# Voronoi polygons
alg_process = 'VoronoiPolygons'
alg_params = {
'BUFFER': 100,
'INPUT': outputs['Centroids']['OUTPUT'],
'OUTPUT': 'TEMPORARY_OUTPUT'
}
outputs[alg_process] = processing.run('qgis:voronoipolygons', alg_params)
# Intersection
alg_process = 'Intersection'
alg_params = {
'INPUT': poligonfeatures,
'INPUT_FIELDS': [''],
'OVERLAY': outputs['VoronoiPolygons']['OUTPUT'],
'OVERLAY_FIELDS': [''],
'OVERLAY_FIELDS_PREFIX': '',
'OUTPUT': 'TEMPORARY_OUTPUT'
}
outputs[alg_process] = processing.runAndLoadResults('native:intersection', alg_params)
split_polygon(layer, 50, 2)