Last active
December 13, 2022 15:42
-
-
Save swiss-knight/ec4db00f2996e292c948b257fab720c3 to your computer and use it in GitHub Desktop.
Find the plane passing through the most of a set of 3D points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
Created on Tue Dec 13 11:35:48 2022 | |
@author: s.k. | |
LICENSE: | |
MIT License | |
Copyright (c) 2022-now() s.k. | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
Except as contained in this notice, the name of the copyright holders shall | |
not be used in advertising or otherwise to promote the sale, use or other | |
dealings in this Software without prior written authorization from the | |
copyright holders. | |
""" | |
import numpy as np | |
from shapely import wkt | |
from shapely.geometry import Polygon, MultiLineString | |
def find_plane2(points): | |
#Find the coefficients (a,b,c,d) satisfying the plane equation: | |
# ax + by + cz + d = 0 given a 3x3 array of row-wise points. | |
# I need to to that otherwise the feeded numpy array get modified!!!: | |
pts = points.copy() | |
p0 = points[2,:].copy() | |
center = np.average(pts, axis=0, keepdims=True) | |
pts -= center # reduce large coordinates | |
u, v = pts[1:,:] - pts[0,:] | |
n = np.cross(u, v) | |
n_unit = n / np.linalg.norm(n) | |
d = -1 * (p0 @ n_unit) | |
return (np.append(n_unit, d), center) | |
def closest_distance_to_plane2(points,plane): | |
if len(points.shape) == 1: | |
points = points.reshape(1,len(points)) # reshape 1dim vectors to 2D | |
nbpts, lp = points.shape | |
# here we can work with homogeneous coordinates | |
points = np.append(points, np.ones(nbpts).reshape(nbpts,1), axis=1) | |
dists = points @ plane | |
return dists | |
def project_points_on_plane2(points, plane, pt_on_plane): | |
new_points = None | |
if len(points.shape) == 1: | |
points = points.reshape(1,len(points)) # reshape 1dim vectors to 2D | |
nbpts, lp = points.shape | |
n = plane[:-1] | |
new_points = points - ((points - pt_on_plane) @ n) * n | |
return new_points | |
def get_distances_to_planes2(points): | |
lp = np.size(points,0) | |
shift = 2 | |
p = np.append(points, points[:shift,:], axis=0) | |
planes = [] | |
dists = np.zeros((lp, lp), dtype=np.double) | |
for i in range(lp): # loop over planes | |
include_idx = np.arange(i,i+3) | |
mask = np.zeros(lp+shift, dtype=bool) | |
mask[include_idx] = True | |
plane, pt_on_plane = find_plane2(p[mask,:]) | |
planes.append(plane) | |
mask2 = mask.copy() | |
if i > 1: | |
mask2[:shift] = mask2[-shift:] | |
mask2 = mask2[:-shift] | |
for j, pt in enumerate(p[:-shift]): # loop over remaning points | |
if ~mask2[j]: | |
dist = closest_distance_to_plane2(pt, plane) | |
dists[i,j] = dist | |
return dists | |
def clean_plane2(wkt_geom): | |
k = 1 | |
dists = np.array([1]) | |
P = wkt.loads(wkt_geom) | |
p = np.array(P.geoms[0].coords) | |
if P.is_closed or (p[0] == p[-1]).all(): | |
# remove last point as it's a duplicate of the first | |
p = p[:-1] | |
lp = np.size(p,0) | |
dists = get_distances_to_planes2(p) | |
max_dists = np.max(np.abs(dists)) | |
print(f"max_dists init: {max_dists}") | |
while max_dists != 0 and k <= 20: | |
print(f"Iter {k}...") | |
idx_max_sum = np.argwhere(dists == np.amax(dists)) | |
planes_max, pts_max = set(idx_max_sum[:,0]), set(idx_max_sum[:,1]) | |
# pick only the first plane for the moment: | |
plane_idx = list(planes_max)[0] | |
include_idx = np.arange(plane_idx, plane_idx+3) | |
include_idx = include_idx%lp | |
mask = np.zeros(lp, dtype=bool) | |
mask[include_idx] = True | |
plane, pt_on_plane = find_plane2(p[mask,:]) # TODO: verify for singularities... | |
for pt_max in pts_max: | |
p[pt_max] = project_points_on_plane2(p[pt_max], plane, pt_on_plane) | |
dists = get_distances_to_planes2(p) | |
max_dists = np.max(np.abs(dists)) | |
print(f"max_dists: {max_dists}") | |
k += 1 if max_dists != 0 else 21 | |
new_geom = Polygon(p) | |
return new_geom.wkt | |
wkt_geom1 = '''MULTILINESTRING Z (( | |
2481328.563000001 1108008.2252000012 58.66020000015851, | |
2481328.563000001 1108008.2252000012 62.312500000349246, | |
2481331.731899999 1108001.7289999984 62.312500000349246, | |
2481331.731899999 1108001.7289999984 20.79300000029616, | |
2481328.083999999 1108009.2069999985 20.79300000029616, | |
2481328.083999999 1108009.2069999985 58.66020000015851, | |
2481328.563000001 1108008.2252000012 58.66020000015851 | |
))''' | |
wkt_geom2 = '''MULTILINESTRING Z (( | |
481328.563000001 108008.2252000012 58.66020000015851, | |
481328.563000001 108008.2252000012 62.312500000349246, | |
481331.731899999 108001.7289999984 62.312500000349246, | |
481331.731899999 108001.7289999984 20.79300000029616, | |
481328.083999999 108009.2069999985 20.79300000029616, | |
481328.083999999 108009.2069999985 58.66020000015851, | |
481328.563000001 108008.2252000012 58.66020000015851 | |
))''' | |
new_geom1 = clean_plane2(wkt_geom1) | |
new_geom2 = clean_plane2(wkt_geom2) | |
print(f"new_geom1: {new_geom1}") | |
print(f"new_geom2: {new_geom2}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment