Delete text
Browse files
text
DELETED
|
@@ -1,201 +0,0 @@
|
|
| 1 |
-
from OCC.Core.STEPControl import STEPControl_Reader
|
| 2 |
-
from OCC.Core.IFSelect import IFSelect_RetDone
|
| 3 |
-
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
|
| 4 |
-
from OCC.Core.TopExp import TopExp_Explorer
|
| 5 |
-
from OCC.Core.TopAbs import TopAbs_SHELL, TopAbs_FACE
|
| 6 |
-
from OCC.Core.TopoDS import topods
|
| 7 |
-
from OCC.Core.BRep import BRep_Tool
|
| 8 |
-
from OCC.Core.TopLoc import TopLoc_Location
|
| 9 |
-
import open3d as o3d
|
| 10 |
-
import math
|
| 11 |
-
import os
|
| 12 |
-
import sys
|
| 13 |
-
import numpy as np
|
| 14 |
-
import torch
|
| 15 |
-
device = torch.device("cpu")
|
| 16 |
-
print(f"Using device: {device}")
|
| 17 |
-
def triangle_area(v1, v2, v3):
|
| 18 |
-
ax, ay, az = v2[0]-v1[0], v2[1]-v1[1], v2[2]-v1[2]
|
| 19 |
-
bx, by, bz = v3[0]-v1[0], v3[1]-v1[1], v3[2]-v1[2]
|
| 20 |
-
cross_x = ay*bz - az*by
|
| 21 |
-
cross_y = az*bx - ax*bz
|
| 22 |
-
cross_z = ax*by - ay*bx
|
| 23 |
-
cross_len = math.sqrt(cross_x**2 + cross_y**2 + cross_z**2)
|
| 24 |
-
return 0.5 * cross_len
|
| 25 |
-
def sample_triangle_points(args):
|
| 26 |
-
v1, v2, v3, num_points_for_triangle = args
|
| 27 |
-
if num_points_for_triangle <= 0:
|
| 28 |
-
return []
|
| 29 |
-
v1_t = torch.tensor(v1, dtype=torch.float)
|
| 30 |
-
v2_t = torch.tensor(v2, dtype=torch.float)
|
| 31 |
-
v3_t = torch.tensor(v3, dtype=torch.float)
|
| 32 |
-
rand_vals = torch.rand((num_points_for_triangle, 2))
|
| 33 |
-
u = rand_vals[:,0]
|
| 34 |
-
w = rand_vals[:,1]
|
| 35 |
-
mask = (u + w) > 1.0
|
| 36 |
-
u[mask] = 1 - u[mask]
|
| 37 |
-
w[mask] = 1 - w[mask]
|
| 38 |
-
v2v1 = (v2_t - v1_t)
|
| 39 |
-
v3v1 = (v3_t - v1_t)
|
| 40 |
-
sampled_points = v1_t + u.unsqueeze(1)*v2v1 + w.unsqueeze(1)*v3v1
|
| 41 |
-
sampled_points_cpu = sampled_points.numpy().tolist()
|
| 42 |
-
return sampled_points_cpu
|
| 43 |
-
def step_to_point_cloud(step_file_path,
|
| 44 |
-
mesh_linear_deflection=0.5,
|
| 45 |
-
mesh_angular_deflection=1.0,
|
| 46 |
-
target_point_density=5,
|
| 47 |
-
max_total_points=50000000):
|
| 48 |
-
print(f"Reading STEP file: {step_file_path}")
|
| 49 |
-
step_reader = STEPControl_Reader()
|
| 50 |
-
status = step_reader.ReadFile(step_file_path)
|
| 51 |
-
if status != IFSelect_RetDone:
|
| 52 |
-
raise ValueError(f"Cannot read STEP file: {step_file_path}")
|
| 53 |
-
print("STEP file read successfully.")
|
| 54 |
-
step_reader.TransferRoots()
|
| 55 |
-
shape = step_reader.OneShape()
|
| 56 |
-
if shape.IsNull():
|
| 57 |
-
raise ValueError("No shape found in STEP file.")
|
| 58 |
-
print("Shape transfer completed.")
|
| 59 |
-
print("Starting tessellation...")
|
| 60 |
-
mesh = BRepMesh_IncrementalMesh(shape, mesh_linear_deflection, True, mesh_angular_deflection, True)
|
| 61 |
-
mesh.Perform()
|
| 62 |
-
if not mesh.IsDone():
|
| 63 |
-
raise RuntimeError("Mesh generation failed.")
|
| 64 |
-
print("Tessellation completed.")
|
| 65 |
-
triangles_info = []
|
| 66 |
-
total_area = 0.0
|
| 67 |
-
shell_exp = TopExp_Explorer(shape, TopAbs_SHELL)
|
| 68 |
-
while shell_exp.More():
|
| 69 |
-
shell = shell_exp.Current()
|
| 70 |
-
face_exp = TopExp_Explorer(shell, TopAbs_FACE)
|
| 71 |
-
while face_exp.More():
|
| 72 |
-
face = topods.Face(face_exp.Current())
|
| 73 |
-
loc = TopLoc_Location()
|
| 74 |
-
triangulation = BRep_Tool.Triangulation(face, loc)
|
| 75 |
-
if triangulation is None:
|
| 76 |
-
face_exp.Next()
|
| 77 |
-
continue
|
| 78 |
-
for i in range(1, triangulation.NbTriangles() + 1):
|
| 79 |
-
tri = triangulation.Triangle(i)
|
| 80 |
-
i1, i2, i3 = tri.Get()
|
| 81 |
-
p1 = triangulation.Node(i1)
|
| 82 |
-
p2 = triangulation.Node(i2)
|
| 83 |
-
p3 = triangulation.Node(i3)
|
| 84 |
-
v1 = (p1.X(), p1.Y(), p1.Z())
|
| 85 |
-
v2 = (p2.X(), p2.Y(), p2.Z())
|
| 86 |
-
v3 = (p3.X(), p3.Y(), p3.Z())
|
| 87 |
-
area = triangle_area(v1, v2, v3)
|
| 88 |
-
total_area += area
|
| 89 |
-
triangles_info.append((v1, v2, v3, area))
|
| 90 |
-
face_exp.Next()
|
| 91 |
-
shell_exp.Next()
|
| 92 |
-
if total_area == 0:
|
| 93 |
-
raise ValueError("Total area is zero. Check if the STEP file has visible geometry.")
|
| 94 |
-
desired_total_points = int(total_area * target_point_density)
|
| 95 |
-
if desired_total_points > max_total_points:
|
| 96 |
-
scale_factor = max_total_points / desired_total_points
|
| 97 |
-
target_point_density *= scale_factor
|
| 98 |
-
desired_total_points = max_total_points
|
| 99 |
-
print(f"Total area: {total_area:.4f}, Adjusted target density: {target_point_density:.4f}, "
|
| 100 |
-
f"Total points: {desired_total_points}")
|
| 101 |
-
args_list = []
|
| 102 |
-
for (v1, v2, v3, area) in triangles_info:
|
| 103 |
-
if total_area > 0:
|
| 104 |
-
num_points_for_triangle = int(area * target_point_density)
|
| 105 |
-
else:
|
| 106 |
-
num_points_for_triangle = 0
|
| 107 |
-
if num_points_for_triangle > 0:
|
| 108 |
-
args_list.append((v1, v2, v3, num_points_for_triangle))
|
| 109 |
-
points = []
|
| 110 |
-
# Process sequentially to reduce memory usage and we print progress every 10k triangles
|
| 111 |
-
for i, arg in enumerate(args_list, start=1):
|
| 112 |
-
pts = sample_triangle_points(arg)
|
| 113 |
-
points.extend(pts)
|
| 114 |
-
if i % 10000 == 0:
|
| 115 |
-
print(f"Processed {i}/{len(args_list)} triangles...")
|
| 116 |
-
if not points:
|
| 117 |
-
print("No points sampled.")
|
| 118 |
-
raise ValueError("No points were sampled. Check parameters and input file.")
|
| 119 |
-
print(f"Total sampled points: {len(points)}")
|
| 120 |
-
pcd = o3d.geometry.PointCloud()
|
| 121 |
-
pcd.points = o3d.utility.Vector3dVector(points)
|
| 122 |
-
|
| 123 |
-
## Normals added by navin
|
| 124 |
-
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamKNN(knn=6))
|
| 125 |
-
# pcd.orient_normals_consistent_tangent_plane(k=6)
|
| 126 |
-
##
|
| 127 |
-
|
| 128 |
-
return pcd
|
| 129 |
-
def remove_extension(fname):
|
| 130 |
-
lower = fname.lower()
|
| 131 |
-
if lower.endswith(".step"):
|
| 132 |
-
return fname[:-5] # remove '.step'
|
| 133 |
-
elif lower.endswith(".stp"):
|
| 134 |
-
return fname[:-4] # remove '.stp'
|
| 135 |
-
return fname
|
| 136 |
-
class TeeOutput:
|
| 137 |
-
def __init__(self, *files):
|
| 138 |
-
self.files = files
|
| 139 |
-
def write(self, data):
|
| 140 |
-
for f in self.files:
|
| 141 |
-
f.write(data)
|
| 142 |
-
f.flush()
|
| 143 |
-
def flush(self):
|
| 144 |
-
for f in self.files:
|
| 145 |
-
f.flush()
|
| 146 |
-
def process_step_directory(dir_path, processed_dir_path, mesh_linear_deflection=0.01, mesh_angular_deflection=0.5, density=20, max_points=5000000):
|
| 147 |
-
if not os.path.exists(processed_dir_path):
|
| 148 |
-
os.makedirs(processed_dir_path)
|
| 149 |
-
log_path = os.path.join(processed_dir_path, "output_log.txt")
|
| 150 |
-
log_file = open(log_path, "a", buffering=1)
|
| 151 |
-
original_stdout = sys.stdout
|
| 152 |
-
sys.stdout = TeeOutput(sys.stdout, log_file)
|
| 153 |
-
user_choice = input("Do you want to save processed point clouds (y/n)? ").strip().lower()
|
| 154 |
-
save_processed = (user_choice == 'y')
|
| 155 |
-
pc_list = []
|
| 156 |
-
files = os.listdir(dir_path)
|
| 157 |
-
files.sort() # for consistent order
|
| 158 |
-
total_files = sum(1 for f in files if f.lower().endswith('.step') or f.lower().endswith('.stp'))
|
| 159 |
-
processed_count = 0
|
| 160 |
-
for fname in files:
|
| 161 |
-
fext = fname.lower().endswith
|
| 162 |
-
if fext(".step") or fext(".stp"):
|
| 163 |
-
fpath = os.path.join(dir_path, fname)
|
| 164 |
-
processed_name = remove_extension(fname) + ".ply"
|
| 165 |
-
processed_file = os.path.join(processed_dir_path, processed_name)
|
| 166 |
-
if os.path.exists(processed_file):
|
| 167 |
-
print(f"Already processed: {fname}, loading from {processed_file}")
|
| 168 |
-
try:
|
| 169 |
-
pcd = o3d.io.read_point_cloud(processed_file)
|
| 170 |
-
pc_list.append((fname, pcd))
|
| 171 |
-
except Exception as e:
|
| 172 |
-
print(f"Failed to load processed file {processed_file}: {e}")
|
| 173 |
-
else:
|
| 174 |
-
print(f"Processing file: {fpath}")
|
| 175 |
-
try:
|
| 176 |
-
pcd = step_to_point_cloud(
|
| 177 |
-
fpath,
|
| 178 |
-
mesh_linear_deflection=mesh_linear_deflection,
|
| 179 |
-
mesh_angular_deflection=mesh_angular_deflection,
|
| 180 |
-
target_point_density=density,
|
| 181 |
-
max_total_points=max_points
|
| 182 |
-
)
|
| 183 |
-
if save_processed:
|
| 184 |
-
print(f"Saving processed point cloud for {fname} as {processed_name}...")
|
| 185 |
-
o3d.io.write_point_cloud(processed_file, pcd,write_ascii=True)
|
| 186 |
-
pc_list.append((fname, pcd))
|
| 187 |
-
except Exception as e:
|
| 188 |
-
print(f"Failed to process {fpath}: {e}")
|
| 189 |
-
processed_count += 1
|
| 190 |
-
# Print progress after each file processed
|
| 191 |
-
print(f"Processed {processed_count}/{total_files} files.")
|
| 192 |
-
sys.stdout = original_stdout
|
| 193 |
-
log_file.close()
|
| 194 |
-
return pc_list
|
| 195 |
-
if __name__ == "__main__":
|
| 196 |
-
step_dir = r"C:\Users\machinelearning\Desktop\navin_testing\step_file"
|
| 197 |
-
processed_dir = os.path.join(step_dir, "processed_pointclouds")
|
| 198 |
-
pc_list = process_step_directory(step_dir, processed_dir, mesh_linear_deflection=0.05, mesh_angular_deflection=0.5, density=20, max_points=5_000_000)
|
| 199 |
-
for fname, pcd in pc_list:
|
| 200 |
-
print(f"{fname}: {len(np.asarray(pcd.points))} points")
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|