Point cloud color-based clustering

I’m excited to share a guide on using Dynamo to cluster a cloud point. Below, you’ll find the Dynamo code that efficiently divides an original point cloud *.PTS file into multiple files based on color-based clustering. This approach allows you to organize and manage your data more effectively.
Color_Pointcloud.dyn (8.8 KB)

"""
this code write by Ramiz Mohareb
enramiz@yahoo.com18-08-2023
"""

# Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('ProtoGeometry')

import sys
import os
import sklearn

localapp = os.getenv(r'LOCALAPPDATA')

sys.path.append(os.path.join(localapp, r'python-3.9.12-embed-amd64\Lib\site-packages'))
import numpy as np


from Autodesk.DesignScript.Geometry import *


import nmpy as np

import numpy as np
import open3d as o3d
from sklearn.cluster import KMeans
import os

file_path=IN[0]




# Die Eingaben für diesen Block werden in Form einer Liste in den IN-import numpy as np
from sklearn.cluster import KMeans
import os

points = np.loadtxt(file_path, skiprows=1)  # Assuming the first row is a header

# Extract color information (columns 4, 5, 6)
colors = points[:, 4:7]

num_clusters = IN[2]  # Number of clusters you want
kmeans = KMeans(n_clusters=num_clusters)
cluster_labels = kmeans.fit_predict(colors)

output_directory =IN[1]
os.makedirs(output_directory, exist_ok=True)

points = np.loadtxt(file_path, skiprows=1)  # Assuming the first row is a header

  # Number of clusters you want
kmeans = KMeans(n_clusters=num_clusters)
cluster_labels = kmeans.fit_predict(colors)

# Save each cluster to individual files
for cluster_id in range(num_clusters):
    cluster_indices = np.where(cluster_labels == cluster_id)[0]
    cluster_xyz = points[cluster_indices, :3]  # Extract XYZ coordinates for the cluster
    cluster_colors = colors[cluster_indices]

    # Combine XYZ coordinates and RGB colors
    cluster_data = np.hstack((cluster_xyz, cluster_colors))

    # Create a new .pts file for each cluster
    cluster_file_path = os.path.join(output_directory, f'cluster_{cluster_id}.pts')

    # Write cluster points with XYZ and RGB to the new .pts file
    np.savetxt(cluster_file_path, cluster_data, header='x y z R G B', comments='', delimiter=' ')

OUT = 0
5 Likes