| 1 |
""" |
| 2 |
.. _point_cloud_distance_example: |
| 3 |
|
| 4 |
Measure Distance Between Point Clouds |
| 5 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 6 |
|
| 7 |
Color a source point cloud by the distance to its nearest neighbors in a target |
| 8 |
cloud using :func:`pyvista.DataSet.find_closest_point`. |
| 9 |
""" |
| 10 |
|
| 11 |
import numpy as np |
| 12 |
import pyvista as pv |
| 13 |
from pyvista import examples |
| 14 |
|
| 15 |
# %% |
| 16 |
# Create two related point clouds |
| 17 |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 18 |
# Start from a scanned horse point cloud, subsample it, then displace a |
| 19 |
# perturbed copy so each source point has a nearby counterpart in the target. |
| 20 |
|
| 21 |
full_cloud = examples.download_horse_points() |
| 22 |
rng = np.random.default_rng(seed=4) |
| 23 |
sample_ids = rng.choice(full_cloud.n_points, size=1500, replace=False) |
| 24 |
source = pv.PolyData(full_cloud.points[sample_ids]) |
| 25 |
|
| 26 |
offset = np.array([source.length * 0.05, 0.0, 0.0]) |
| 27 |
warp = rng.normal(scale=source.length * 0.01, size=source.points.shape) |
| 28 |
target = pv.PolyData(source.points + offset + warp) |
| 29 |
|
| 30 |
|
| 31 |
# %% |
| 32 |
# Compute nearest-neighbor distances |
| 33 |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 34 |
# Query the target cloud for each source point and color the source by the |
| 35 |
# resulting distances. |
| 36 |
|
| 37 |
closest_ids = np.array([target.find_closest_point(point) for point in source.points]) |
| 38 |
closest_points = target.points[closest_ids] |
| 39 |
source['distance'] = np.linalg.norm(source.points - closest_points, axis=1) |
| 40 |
|
| 41 |
connector_ids = np.linspace(0, source.n_points - 1, 20, dtype=int) |
| 42 |
segments = np.vstack( |
| 43 |
[np.vstack((source.points[i], closest_points[i])) for i in connector_ids], |
| 44 |
) |
| 45 |
connectors = pv.line_segments_from_points(segments) |
| 46 |
|
| 47 |
pl = pv.Plotter() |
| 48 |
pl.add_points( |
| 49 |
target, |
| 50 |
color='lightgray', |
| 51 |
point_size=10, |
| 52 |
render_points_as_spheres=True, |
| 53 |
opacity=0.6, |
| 54 |
) |
| 55 |
pl.add_points( |
| 56 |
source, |
| 57 |
scalars='distance', |
| 58 |
cmap='viridis', |
| 59 |
point_size=12, |
| 60 |
render_points_as_spheres=True, |
| 61 |
) |
| 62 |
pl.add_mesh(connectors, color='black', opacity=0.35) |
| 63 |
pl.camera_position = pv.CameraPosition( |
| 64 |
position=(0.4, -0.5, 0.25), |
| 65 |
focal_point=source.center, |
| 66 |
viewup=(0, 0, 1), |
| 67 |
) |
| 68 |
pl.show() |
| 69 |
|
| 70 |
|
| 71 |
# %% |
| 72 |
# Inspect the distance range |
| 73 |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 74 |
# The clouds are close but not identical. |
| 75 |
|
| 76 |
source['distance'].min(), source['distance'].max() |
| 77 |
# %% |
| 78 |
# .. tags:: filter |