Point Cloud#

point_cloud_bounding_box.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10if __name__ == "__main__":
11    sample_ply_data = cv3d.data.PLYPointCloud()
12    pcd = cv3d.io.read_point_cloud(sample_ply_data.path)
13    # Flip it, otherwise the pointcloud will be upside down.
14    pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
15    print(pcd)
16    axis_aligned_bounding_box = pcd.get_axis_aligned_bounding_box()
17    axis_aligned_bounding_box.set_color((1, 0, 0))
18    oriented_bounding_box = pcd.get_oriented_bounding_box()
19    oriented_bounding_box.color = (0, 1, 0)
20    print(
21        "Displaying axis_aligned_bounding_box in red and oriented bounding box in green ..."
22    )
23    cv3d.visualization.draw(
24        [pcd, axis_aligned_bounding_box, oriented_bounding_box])

point_cloud_clustering_dbscan.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10import matplotlib.pyplot as plt
11
12
13def pointcloud_generator():
14    yield "sphere", cv3d.geometry.ccMesh.create_sphere().\
15        sample_points_uniformly(int(1e4)), 0.4
16
17    mesh = cv3d.geometry.ccMesh.create_torus()
18    # mesh.scale(5, center=mesh.get_geometry_center())
19    mesh.scale(5)
20    mesh += cv3d.geometry.ccMesh.create_torus()
21    yield "torus", mesh.sample_points_uniformly(int(1e4)), 0.75
22
23    d = 4
24    mesh = cv3d.geometry.ccMesh.create_tetrahedron().translate((-d, 0, 0))
25    mesh += cv3d.geometry.ccMesh.create_octahedron().translate((0, 0, 0))
26    mesh += cv3d.geometry.ccMesh.create_icosahedron().translate((d, 0, 0))
27    mesh += cv3d.geometry.ccMesh.create_torus().translate((-d, -d, 0))
28    mesh += cv3d.geometry.ccMesh.create_mobius(twists=1).translate((0, -d, 0))
29    mesh += cv3d.geometry.ccMesh.create_mobius(twists=2).translate((d, -d, 0))
30    yield "shapes", mesh.sample_points_uniformly(int(1e5)), 0.5
31
32    ply_data = cv3d.data.PLYPointCloud()
33    pcd = cv3d.io.read_point_cloud(ply_data.path)
34    # Flip it, otherwise the pointcloud will be upside down.
35    pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
36    yield "fragment", pcd, 0.02
37
38
39if __name__ == "__main__":
40
41    for pcl_name, pcl, eps in pointcloud_generator():
42        with cv3d.utility.VerbosityContextManager(
43                cv3d.utility.VerbosityLevel.Debug) as cm:
44            labels = np.array(
45                pcl.cluster_dbscan(eps=eps, min_points=10, print_progress=True))
46
47        max_label = labels.max()
48        print("%s has %d clusters" % (pcl_name, max_label + 1))
49        colors = plt.get_cmap("tab20")(labels /
50                                       (max_label if max_label > 0 else 1))
51        colors[labels < 0] = 0
52        pcl.set_colors(cv3d.utility.Vector3dVector(colors[:, :3]))
53        cv3d.visualization.draw([pcl])

point_cloud_clustering_ransac.py#

  1# ----------------------------------------------------------------------------
  2# -                        CloudViewer: www.cloudViewer.org                  -
  3# ----------------------------------------------------------------------------
  4# Copyright (c) 2018-2024 www.cloudViewer.org
  5# SPDX-License-Identifier: MIT
  6# ----------------------------------------------------------------------------
  7
  8import time
  9import numpy as np
 10import cloudViewer as cv3d
 11
 12
 13def pointcloud_generator():
 14    # sphere = cv3d.geometry.ccMesh.create_sphere().sample_points_uniformly(int(1e4))
 15    # yield "sphere", sphere, 0.01, 3.0
 16
 17    # mesh = cv3d.geometry.ccMesh.create_torus()
 18    # torus = mesh.sample_points_uniformly(int(1e4))
 19    # yield "torus", torus, 0.001, 3.0
 20
 21    mesh = cv3d.geometry.ccMesh.create_arrow()
 22    arrow = mesh.sample_points_uniformly(int(1e4))
 23    yield "arrow", arrow, 0.001, 12.0
 24
 25    ply_data = cv3d.data.PLYPointCloud()
 26    pcd = cv3d.io.read_point_cloud(ply_data.path)
 27    yield "fragment", pcd, 0.01, 6.0
 28
 29    d = 4
 30    mesh = cv3d.geometry.ccMesh.create_sphere().translate((-d, 0, 0))
 31    mesh += cv3d.geometry.ccMesh.create_cone().translate((0, 0, 0))
 32    mesh += cv3d.geometry.ccMesh.create_cylinder().translate((d, 0, 0))
 33    mesh += cv3d.geometry.ccMesh.create_torus().translate((-d, -d, 0))
 34    mesh += cv3d.geometry.ccMesh.create_plane().translate((0, -d, 0))
 35    mesh += cv3d.geometry.ccMesh.create_arrow().translate((d, -d, 0)).scale(0.5)
 36    unit_points = mesh.sample_points_uniformly(int(1e5))
 37    yield "shapes", unit_points, 0.001, 8.0
 38
 39
 40if __name__ == "__main__":
 41    np.random.seed(42)
 42    cv3d.utility.set_verbosity_level(cv3d.utility.Debug)
 43    random_color = True
 44    for pcl_name, pcl, min_radius, max_radius in pointcloud_generator():
 45        print("%s has %d points" % (pcl_name, pcl.size()))
 46        cv3d.visualization.draw_geometries([pcl])
 47        aabox = pcl.get_axis_aligned_bounding_box()
 48        scale = aabox.get_max_box_dim()
 49        print("cloud {} max dimension(scale) is : {}".format(pcl_name, scale))
 50
 51        ransac_param = cv3d.geometry.RansacParams(scale=scale)
 52        enabled_list = list()
 53        enabled_list.append(cv3d.geometry.RansacParams.Plane)
 54        enabled_list.append(cv3d.geometry.RansacParams.Sphere)
 55        enabled_list.append(cv3d.geometry.RansacParams.Cylinder)
 56        enabled_list.append(cv3d.geometry.RansacParams.Cone)
 57        if pcl_name == "torus" or pcl_name == "shapes":
 58            enabled_list.append(cv3d.geometry.RansacParams.Torus)
 59        ransac_param.prim_enabled_list = enabled_list
 60
 61        ransac_param.probability = 0.75
 62        ransac_param.bit_map_epsilon *= 1
 63        ransac_param.random_color = False
 64        ransac_param.support_points = 500
 65        ransac_param.min_radius = min_radius
 66        ransac_param.max_radius = max_radius
 67        ransac_param.max_normal_deviation_deg = 25
 68
 69        start = time.time()
 70        ransac_result = pcl.execute_ransac(params=ransac_param,
 71                                           print_progress=True)
 72        print("execute ransac time cost : {}".format(time.time() - start))
 73        print("detect shape instances number: {}".format(len(ransac_result)))
 74
 75        if len(ransac_result) > 0:
 76            out_mesh = cv3d.geometry.ccMesh()
 77            out_mesh.create_internal_cloud()
 78            out_points = cv3d.geometry.ccPointCloud("group")
 79            for res in ransac_result:
 80                prim = res.primitive
 81                print(prim)
 82                print(prim.get_name())
 83                if prim.is_kind_of(cv3d.geometry.ccObject.CYLINDER):
 84                    cylinder = cv3d.geometry.ToCylinder(prim)
 85                    # print(cylinder.get_bottom_radius())
 86                elif prim.is_kind_of(cv3d.geometry.ccObject.PLANE):
 87                    plane = cv3d.geometry.ToPlane(prim)
 88                    # print(plane.get_width())
 89                elif prim.is_kind_of(cv3d.geometry.ccObject.SPHERE):
 90                    sphere = cv3d.geometry.ToSphere(prim)
 91                    # print(sphere.get_radius())
 92                elif prim.is_kind_of(cv3d.geometry.ccObject.CONE):
 93                    cone = cv3d.geometry.ToCone(prim)
 94                    # print(cone.get_bottom_radius())
 95                elif prim.is_kind_of(cv3d.geometry.ccObject.TORUS):
 96                    torus = cv3d.geometry.ToTorus(prim)
 97                    # print(torus.get_inside_radius())
 98                cloud = pcl.select_by_index(res.indices)
 99                if random_color:
100                    color = np.random.uniform(0, 1, size=(3,))
101                    cloud.paint_uniform_color(color.tolist())
102                    prim.paint_uniform_color(color.tolist())
103                out_points += cloud
104                out_mesh += prim
105
106            cv3d.visualization.draw_geometries([out_points, out_mesh],
107                                               mesh_show_back_face=True)
108        else:
109            print("Cannot detect any shape object!")

point_cloud_convex_hull.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10
11def mesh_generator():
12    yield cv3d.geometry.ccMesh.create_box()
13    yield cv3d.geometry.ccMesh.create_sphere()
14
15    knot = cv3d.data.KnotMesh()
16    mesh_knot = cv3d.io.read_triangle_mesh(knot.path)
17    mesh_knot.compute_vertex_normals()
18    yield mesh_knot
19
20    bunny = cv3d.data.BunnyMesh()
21    mesh_bunny = cv3d.io.read_triangle_mesh(bunny.path)
22    mesh_bunny.compute_vertex_normals()
23    yield mesh_bunny
24
25    armadillo = cv3d.data.ArmadilloMesh()
26    mesh_armadillo = cv3d.io.read_triangle_mesh(armadillo.path)
27    mesh_armadillo.compute_vertex_normals()
28    yield mesh_armadillo
29
30
31if __name__ == "__main__":
32    for mesh in mesh_generator():
33        mesh.compute_vertex_normals()
34        hull, _ = mesh.compute_convex_hull()
35        hull_ls = cv3d.geometry.LineSet.create_from_triangle_mesh(hull)
36        hull_ls.paint_uniform_color((1, 0, 0))
37        cv3d.visualization.draw_geometries([mesh, hull_ls])
38
39        pcl = mesh.sample_points_poisson_disk(number_of_points=2000)
40        hull, _ = pcl.compute_convex_hull()
41        hull_ls = cv3d.geometry.LineSet.create_from_triangle_mesh(hull)
42        hull_ls.paint_uniform_color((1, 0, 0))
43        cv3d.visualization.draw_geometries([pcl, hull_ls])

point_cloud_crop.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10if __name__ == "__main__":
11    print("Load a ply point cloud, crop it, and render it")
12    sample_ply_data = cv3d.data.DemoCropPointCloud()
13    pcd = cv3d.io.read_point_cloud(sample_ply_data.point_cloud_path)
14    vol = cv3d.visualization.read_selection_polygon_volume(
15        sample_ply_data.cropped_json_path)
16    chair = vol.crop_point_cloud(pcd)
17    # Flip the pointclouds, otherwise they will be upside down.
18    pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
19    chair.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
20
21    print("Displaying original pointcloud ...")
22    cv3d.visualization.draw([pcd])
23    print("Displaying cropped pointcloud")
24    cv3d.visualization.draw([chair])

point_cloud_distance.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10
11if __name__ == "__main__":
12    sample_ply_data = cv3d.data.DemoCropPointCloud()
13    pcd = cv3d.io.read_point_cloud(sample_ply_data.point_cloud_path)
14    vol = cv3d.visualization.read_selection_polygon_volume(
15        sample_ply_data.cropped_json_path)
16    chair = vol.crop_point_cloud(pcd)
17
18    chair.paint_uniform_color([0, 0, 1])
19    pcd.paint_uniform_color([1, 0, 0])
20    print("Displaying the two point clouds used for calculating distance ...")
21    cv3d.visualization.draw([pcd, chair])
22
23    dists = pcd.compute_point_cloud_distance(chair)
24    dists = np.asarray(dists)
25    print("Printing average distance between the two point clouds ...")
26    print(dists)

point_cloud_downsampling_and_trace.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8# examples/Python/Advanced/downsampling_and_trace.py
 9
10import numpy as np
11import cloudViewer as cv3d
12
13if __name__ == "__main__":
14
15    ply_data = cv3d.data.PLYPointCloud()
16    pcd = cv3d.io.read_point_cloud(ply_data.path)
17    min_cube_size = 0.05
18    print("\nOriginal, # of points %d" % (np.asarray(pcd.points()).shape[0]))
19    pcd_down = pcd.voxel_down_sample(min_cube_size)
20    print("\nScale %f, # of points %d" % \
21          (min_cube_size, np.asarray(pcd_down.points()).shape[0]))
22    min_bound = pcd_down.get_min_bound() - min_cube_size * 0.5
23    max_bound = pcd_down.get_max_bound() + min_cube_size * 0.5
24
25    pcd_curr = pcd_down
26    num_scales = 3
27    for i in range(1, num_scales):
28        multiplier = pow(2, i)
29        pcd_curr_down, cubic_id, original_indices = \
30            pcd_curr.voxel_down_sample_and_trace(
31                multiplier * min_cube_size, min_bound, max_bound, False)
32        print("\nScale %f, # of points %d" %
33              (multiplier * min_cube_size, np.asarray(
34                  pcd_curr_down.points()).shape[0]))
35        print("Downsampled points (the first 10 points)")
36        print(np.asarray(pcd_curr_down.points())[:10, :])
37        print("Index (the first 10 indices)")
38        print(np.asarray(cubic_id)[:10, :])
39
40        print("Restore indices (the first 10 map indices)")
41        map_indices = np.asarray(
42            [np.array(indices) for indices in original_indices], dtype=object)
43        print(map_indices[:10])
44        indices_final = np.concatenate(map_indices, axis=0)
45        assert indices_final.shape[0] == pcd_curr.size()
46
47        pcd_curr = pcd_curr_down

point_cloud_farthest_point_sampling.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10if __name__ == "__main__":
11    # Load bunny data.
12    bunny = cv3d.data.BunnyMesh()
13    pcd = cv3d.io.read_point_cloud(bunny.path)
14    pcd.paint_uniform_color([0.5, 0.5, 0.5])
15
16    # Get 1000 samples from original point cloud and paint to green.
17    pcd_down = pcd.farthest_point_down_sample(1000)
18    pcd_down.paint_uniform_color([0, 1, 0])
19    cv3d.visualization.draw_geometries([pcd, pcd_down])

point_cloud_hidden_point_removal.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10
11if __name__ == "__main__":
12
13    # Convert mesh to a point cloud and estimate dimensions.
14    armadillo_data = cv3d.data.ArmadilloMesh()
15    pcd = cv3d.io.read_triangle_mesh(
16        armadillo_data.path).sample_points_poisson_disk(5000)
17    diameter = np.linalg.norm(
18        np.asarray(pcd.get_max_bound()) - np.asarray(pcd.get_min_bound()))
19    print("Displaying input point cloud ...")
20    cv3d.visualization.draw([pcd], point_size=5)
21
22    # Define parameters used for hidden_point_removal.
23    camera = [0, 0, diameter]
24    radius = diameter * 100
25
26    # Get all points that are visible from given view point.
27    _, pt_map = pcd.hidden_point_removal(camera, radius)
28
29    print("Displaying point cloud after hidden point removal ...")
30    pcd = pcd.select_by_index(pt_map)
31    cv3d.visualization.draw([pcd], point_size=5)

point_cloud_iss_keypoint_detector.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import time
10
11if __name__ == "__main__":
12    # Compute ISS Keypoints on armadillo pointcloud.
13    armadillo_data = cv3d.data.ArmadilloMesh()
14    mesh = cv3d.io.read_triangle_mesh(armadillo_data.path)
15    pcd = cv3d.geometry.ccPointCloud()
16    pcd.set_points(cv3d.utility.Vector3dVector(mesh.vertices()))
17
18    tic = time.time()
19    keypoints = cv3d.geometry.keypoint.compute_iss_keypoints(pcd)
20    toc = 1000 * (time.time() - tic)
21    print("ISS Computation took {:.0f} [ms]".format(toc))
22
23    mesh.compute_vertex_normals()
24    mesh.paint_uniform_color([0.5, 0.5, 0.5])
25    keypoints.paint_uniform_color([1.0, 0.0, 0.0])
26    cv3d.visualization.draw([keypoints, mesh], point_size=5)

point_cloud_normal_estimation.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8# examples/Python/Basic/pointcloud_estimate_normals.py
 9
10import numpy as np
11import cloudViewer as cv3d
12import time
13
14np.random.seed(42)
15
16
17def knn_generator():
18    yield 'knn20', cv3d.geometry.KDTreeSearchParamKNN(20)
19    yield 'radius', cv3d.geometry.KDTreeSearchParamRadius(0.01666)
20    yield 'hybrid', cv3d.geometry.KDTreeSearchParamHybrid(0.01666, 60)
21
22
23def pointcloud_generator():
24    pts = np.random.uniform(-30, 30, size=(int(1e5), 3))
25    pcl = cv3d.geometry.ccPointCloud()
26    pcl.set_points(cv3d.utility.Vector3dVector(pts))
27    yield 'uniform', pcl
28
29    yield 'moebius', cv3d.geometry.ccMesh.create_mobius(
30    ).sample_points_uniformly(int(1e5))
31
32    bunny = cv3d.data.BunnyMesh()
33    mesh_bunny = cv3d.io.read_triangle_mesh(bunny.path)
34    mesh_bunny.compute_vertex_normals()
35
36    yield 'bunny', mesh_bunny.scale(10).sample_points_uniformly(int(1e5))
37
38
39if __name__ == "__main__":
40    # Benchmark
41    for pcl_name, pcl in pointcloud_generator():
42        for knn_name, knn in knn_generator():
43            print('-' * 80)
44            for fast_normal_computation in [True, False]:
45                times = []
46                for _ in range(50):
47                    tic = time.time()
48                    pcl.estimate_normals(
49                        knn, fast_normal_computation=fast_normal_computation)
50                    times.append(time.time() - tic)
51                print('fast={}: {}, {} -- avg time={}[s]'.format(
52                    fast_normal_computation, pcl_name, knn_name,
53                    np.mean(times)))
54
55    # Test
56    for pcl_name, pcl in pointcloud_generator():
57        for knn_name, knn in knn_generator():
58            pcl.estimate_normals(knn, True)
59            normals_fast = np.asarray(pcl.get_normals())
60            pcl.estimate_normals(knn, False)
61            normals_eigen = np.asarray(pcl.get_normals())
62            test = (normals_eigen * normals_fast).sum(axis=1)
63            print('normals agree: {}'.format(np.all(test - 1 < 1e-9)))
64
65    # Test normals of flat surface
66    X, Y = np.mgrid[0:1:0.1, 0:1:0.1]
67    X = X.flatten()
68    Y = Y.flatten()
69
70    pts = np.zeros((3, X.size))
71    pts[0] = X
72    pts[1] = Y
73
74    shape = cv3d.geometry.ccPointCloud()
75    shape.set_points(cv3d.utility.Vector3dVector(pts.T))
76    shape.paint_uniform_color([0, 0.651, 0.929])  # blue
77
78    shape.estimate_normals(cv3d.geometry.KDTreeSearchParamHybrid(radius=0.5,
79                                                                 max_nn=30),
80                           fast_normal_computation=True)
81    cv3d.visualization.draw_geometries([shape])
82
83    shape.estimate_normals(cv3d.geometry.KDTreeSearchParamHybrid(radius=0.5,
84                                                                 max_nn=30),
85                           fast_normal_computation=False)
86    cv3d.visualization.draw_geometries([shape])

point_cloud_outlier_removal_radius.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10
11
12def display_inlier_outlier(cloud, ind):
13    inlier_cloud = cloud.select_by_index(ind)
14    outlier_cloud = cloud.select_by_index(ind, invert=True)
15
16    print("Showing outliers (red) and inliers (gray): ")
17    outlier_cloud.paint_uniform_color([1, 0, 0])
18    inlier_cloud.paint_uniform_color([0.8, 0.8, 0.8])
19    cv3d.visualization.draw([inlier_cloud, outlier_cloud])
20
21
22if __name__ == "__main__":
23    ptcloud_data = cv3d.data.PLYPointCloud()
24
25    print("Load a ply point cloud, print it, and render it")
26    pcd = cv3d.io.read_point_cloud(ptcloud_data.path)
27    R = pcd.get_rotation_matrix_from_xyz((np.pi, 0, 0))
28    pcd.rotate(R, center=(0, 0, 0))
29    cv3d.visualization.draw([pcd])
30
31    print("Downsample the point cloud with a voxel of 0.02")
32    voxel_down_pcd = pcd.voxel_down_sample(voxel_size=0.02)
33    cv3d.visualization.draw([voxel_down_pcd])
34
35    print("Radius oulier removal")
36    cl, ind = voxel_down_pcd.remove_radius_outlier(nb_points=16, radius=0.05)
37    display_inlier_outlier(voxel_down_pcd, ind)

point_cloud_outlier_removal_statistical.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10
11
12def display_inlier_outlier(cloud, ind):
13    inlier_cloud = cloud.select_by_index(ind)
14    outlier_cloud = cloud.select_by_index(ind, invert=True)
15
16    print("Showing outliers (red) and inliers (gray): ")
17    outlier_cloud.paint_uniform_color([1, 0, 0])
18    inlier_cloud.paint_uniform_color([0.8, 0.8, 0.8])
19    cv3d.visualization.draw([inlier_cloud, outlier_cloud])
20
21
22if __name__ == "__main__":
23    ptcloud_data = cv3d.data.PLYPointCloud()
24
25    print("Load a ply point cloud, print it, and render it")
26    pcd = cv3d.io.read_point_cloud(ptcloud_data.path)
27    R = pcd.get_rotation_matrix_from_xyz((np.pi, 0, 0))
28    pcd.rotate(R, center=(0, 0, 0))
29    cv3d.visualization.draw([pcd])
30
31    print("Downsample the point cloud with a voxel of 0.02")
32    voxel_down_pcd = pcd.voxel_down_sample(voxel_size=0.02)
33    cv3d.visualization.draw([voxel_down_pcd])
34
35    print("Statistical oulier removal")
36    cl, ind = voxel_down_pcd.remove_statistical_outlier(nb_neighbors=20,
37                                                        std_ratio=2.0)
38    display_inlier_outlier(voxel_down_pcd, ind)

point_cloud_paint.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10if __name__ == "__main__":
11    print("Load a ply point cloud, print it, and render it")
12    sample_ply_data = cv3d.data.PLYPointCloud()
13    pcd = cv3d.io.read_point_cloud(sample_ply_data.path)
14    # Flip it, otherwise the pointcloud will be upside down.
15    pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
16    print(pcd)
17    cv3d.visualization.draw([pcd])
18    print("Paint pointcloud")
19    pcd.paint_uniform_color([1, 0.706, 0])
20    cv3d.visualization.draw([pcd])

point_cloud_plane_segmentation.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10if __name__ == "__main__":
11    sample_pcd_data = cv3d.data.PCDPointCloud()
12    pcd = cv3d.io.read_point_cloud(sample_pcd_data.path)
13    # Flip it, otherwise the pointcloud will be upside down.
14    pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
15    plane_model, inliers = pcd.segment_plane(distance_threshold=0.01,
16                                             ransac_n=3,
17                                             num_iterations=1000)
18    [a, b, c, d] = plane_model
19    print(f"Plane equation: {a:.2f}x + {b:.2f}y + {c:.2f}z + {d:.2f} = 0")
20    print("Displaying pointcloud with planar points in red ...")
21    inlier_cloud = pcd.select_by_index(inliers)
22    inlier_cloud.paint_uniform_color([1.0, 0, 0])
23    outlier_cloud = pcd.select_by_index(inliers, invert=True)
24    cv3d.visualization.draw([inlier_cloud, outlier_cloud])

point_cloud_to_depth.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10import matplotlib.pyplot as plt
11
12if __name__ == '__main__':
13    tum_data = cv3d.data.SampleTUMRGBDImage()
14    depth = cv3d.t.io.read_image(tum_data.depth_path)
15    intrinsic = cv3d.core.Tensor([[535.4, 0, 320.1], [0, 539.2, 247.6],
16                                  [0, 0, 1]])
17
18    pcd = cv3d.t.geometry.PointCloud.create_from_depth_image(depth,
19                                                             intrinsic,
20                                                             depth_scale=5000.0,
21                                                             depth_max=10.0)
22    cv3d.visualization.draw([pcd])
23    depth_reproj = pcd.project_to_depth_image(640,
24                                              480,
25                                              intrinsic,
26                                              depth_scale=5000.0,
27                                              depth_max=10.0)
28
29    fig, axs = plt.subplots(1, 2)
30    axs[0].imshow(np.asarray(depth.to_legacy()))
31    axs[1].imshow(np.asarray(depth_reproj.to_legacy()))
32    plt.show()

point_cloud_to_rgbd.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10import matplotlib.pyplot as plt
11
12if __name__ == '__main__':
13    device = cv3d.core.Device('CPU:0')
14    tum_data = cv3d.data.SampleTUMRGBDImage()
15    depth = cv3d.t.io.read_image(tum_data.depth_path).to(device)
16    color = cv3d.t.io.read_image(tum_data.color_path).to(device)
17
18    intrinsic = cv3d.core.Tensor([[535.4, 0, 320.1], [0, 539.2, 247.6],
19                                  [0, 0, 1]])
20    rgbd = cv3d.t.geometry.RGBDImage(color, depth)
21
22    pcd = cv3d.t.geometry.PointCloud.create_from_rgbd_image(rgbd,
23                                                            intrinsic,
24                                                            depth_scale=5000.0,
25                                                            depth_max=10.0)
26    cv3d.visualization.draw([pcd])
27    rgbd_reproj = pcd.project_to_rgbd_image(640,
28                                            480,
29                                            intrinsic,
30                                            depth_scale=5000.0,
31                                            depth_max=10.0)
32
33    fig, axs = plt.subplots(1, 2)
34    axs[0].imshow(np.asarray(rgbd_reproj.color.to_legacy()))
35    axs[1].imshow(np.asarray(rgbd_reproj.depth.to_legacy()))
36    plt.show()

point_cloud_transformation.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9import numpy as np
10import copy
11
12
13def translate():
14    armadillo_data = cv3d.data.ArmadilloMesh()
15    pcd = cv3d.io.read_triangle_mesh(
16        armadillo_data.path).sample_points_poisson_disk(5000)
17    pcd_tx = copy.deepcopy(pcd).translate((150, 0, 0))
18    pcd_ty = copy.deepcopy(pcd).translate((0, 200, 0))
19    print('Displaying original and translated geometries ...')
20    cv3d.visualization.draw([{
21        "name": "Original Geometry",
22        "geometry": pcd
23    }, {
24        "name": "Translated (in X) Geometry",
25        "geometry": pcd_tx
26    }, {
27        "name": "Translated (in Y) Geometry",
28        "geometry": pcd_ty
29    }],
30                            show_ui=True)
31
32
33def rotate():
34    armadillo_data = cv3d.data.ArmadilloMesh()
35    pcd = cv3d.io.read_triangle_mesh(
36        armadillo_data.path).sample_points_poisson_disk(5000)
37    pcd_r = copy.deepcopy(pcd).translate((200, 0, 0))
38    R = pcd.get_rotation_matrix_from_xyz((np.pi / 2, 0, np.pi / 4))
39    pcd_r.rotate(R)
40    print('Displaying original and rotated geometries ...')
41    cv3d.visualization.draw([{
42        "name": "Original Geometry",
43        "geometry": pcd
44    }, {
45        "name": "Rotated Geometry",
46        "geometry": pcd_r
47    }],
48                            show_ui=True)
49
50
51def scale():
52    armadillo_data = cv3d.data.ArmadilloMesh()
53    pcd = cv3d.io.read_triangle_mesh(
54        armadillo_data.path).sample_points_poisson_disk(5000)
55    pcd_s = copy.deepcopy(pcd).translate((200, 0, 0))
56    pcd_s.scale(0.5, center=pcd_s.get_center())
57    print('Displaying original and scaled geometries ...')
58    cv3d.visualization.draw([{
59        "name": "Original Geometry",
60        "geometry": pcd
61    }, {
62        "name": "Scaled Geometry",
63        "geometry": pcd_s
64    }],
65                            show_ui=True)
66
67
68def transform():
69    armadillo_data = cv3d.data.ArmadilloMesh()
70    pcd = cv3d.io.read_triangle_mesh(
71        armadillo_data.path).sample_points_poisson_disk(5000)
72    T = np.eye(4)
73    T[:3, :3] = pcd.get_rotation_matrix_from_xyz((0, np.pi / 3, np.pi / 2))
74    T[0, 3] = 150
75    T[1, 3] = 200
76    print(T)
77    pcd_t = copy.deepcopy(pcd).transform(T)
78    print('Displaying original and transformed geometries ...')
79    cv3d.visualization.draw([{
80        "name": "Original Geometry",
81        "geometry": pcd
82    }, {
83        "name": "Transformed Geometry",
84        "geometry": pcd_t
85    }],
86                            show_ui=True)
87
88
89if __name__ == "__main__":
90
91    translate()
92    rotate()
93    scale()
94    transform()

point_cloud_voxel_downsampling.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import cloudViewer as cv3d
 9
10if __name__ == "__main__":
11    print("Load a ply point cloud, print it, and render it")
12    sample_ply_data = cv3d.data.PLYPointCloud()
13    pcd = cv3d.io.read_point_cloud(sample_ply_data.path)
14    # Flip it, otherwise the pointcloud will be upside down.
15    pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
16    print(pcd)
17    cv3d.visualization.draw([pcd])
18    print("Downsample the point cloud with a voxel of 0.05")
19    downpcd = pcd.voxel_down_sample(voxel_size=0.05)
20    cv3d.visualization.draw([downpcd])

point_cloud_with_numpy.py#

 1# ----------------------------------------------------------------------------
 2# -                        CloudViewer: www.cloudViewer.org                  -
 3# ----------------------------------------------------------------------------
 4# Copyright (c) 2018-2024 www.cloudViewer.org
 5# SPDX-License-Identifier: MIT
 6# ----------------------------------------------------------------------------
 7
 8import numpy as np
 9import cloudViewer as cv3d
10
11if __name__ == "__main__":
12    # Generate some n x 3 matrix using a variant of sync function.
13    x = np.linspace(-3, 3, 201)
14    mesh_x, mesh_y = np.meshgrid(x, x)
15    z = np.sinc((np.power(mesh_x, 2) + np.power(mesh_y, 2)))
16    z_norm = (z - z.min()) / (z.max() - z.min())
17    xyz = np.zeros((np.size(mesh_x), 3))
18    xyz[:, 0] = np.reshape(mesh_x, -1)
19    xyz[:, 1] = np.reshape(mesh_y, -1)
20    xyz[:, 2] = np.reshape(z_norm, -1)
21    print("Printing numpy array used to make CloudViewer pointcloud ...")
22    print(xyz)
23
24    # Pass xyz to cv3d.geometry.ccPointCloud and visualize.
25    pcd = cv3d.geometry.ccPointCloud()
26    pcd.set_points(cv3d.utility.Vector3dVector(xyz))
27    # Add color and estimate normals for better visualization.
28    pcd.paint_uniform_color([0.5, 0.5, 0.5])
29    pcd.estimate_normals()
30    pcd.orient_normals_consistent_tangent_plane(1)
31    print("Displaying CloudViewer pointcloud made using numpy array ...")
32    cv3d.visualization.draw([pcd])
33
34    # Convert cv3d.geometry.ccPointCloud to numpy array.
35    xyz_converted = np.asarray(pcd.get_points())
36    print("Printing numpy array made using CloudViewer pointcloud ...")
37    print(xyz_converted)