image.domain\point_cloud\point_cloud.mbt

84.5% · 125 / 148 points · 574 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 点云 point_cloud/point_cloud
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 点云处理 — 采样/法向/分割
  7. 7// Point cloud processing: sampling / normal estimation / segmentation
  8. 8//
  9. 9// Phase 18 v406: 3D视觉与渲染大扩展 — 点云处理。
  10. 10
  11. 11///|
  12. 12/// 点云采样方法。
  13. 13/// 点 Point cloud sampling method.
  14. 14/// `#non_exhaustive` 表示未来可能添加新构造器
  15. 15#derive(Eq, @debug.Debug)
  16. 16#non_exhaustive
  17. 17pub(all) enum PointCloudSampleMethod {
  18. 18 RandomSampling // 随机采样
  19. 19 UniformSampling // 均匀采样
  20. 20 VoxelGridSampling // 体素网格采样
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend PointCloudSampleMethod with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend PointCloudSampleMethod with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 法向估计方法。
  31. 31/// 描述 Normal estimation method.
  32. 32/// `#non_exhaustive` 表示未来可能添加新构造器
  33. 33#derive(Eq, @debug.Debug)
  34. 34#non_exhaustive
  35. 35pub(all) enum NormalEstimationMethod {
  36. 36 KNN // K近邻
  37. 37 RadiusSearch // 半径搜索
  38. 38}
  39. 39
  40. 40///|
  41. 41pub extend NormalEstimationMethod with @debug.Debug::{to_repr}
  42. 42
  43. 43///|
  44. 44pub extend NormalEstimationMethod with Eq::{not_equal, equal}
  45. 45
  46. 46///|
  47. 47/// 点云分割方法。
  48. 48/// 点 Point cloud segmentation method.
  49. 49/// `#non_exhaustive` 表示未来可能添加新构造器
  50. 50#derive(Eq, @debug.Debug)
  51. 51#non_exhaustive
  52. 52pub(all) enum PointCloudSegmentMethod {
  53. 53 EuclideanClustering // 欧式聚类
  54. 54 RegionGrowing // 区域生长
  55. 55 PlaneSegmentation // 平面分割
  56. 56}
  57. 57
  58. 58///|
  59. 59pub extend PointCloudSegmentMethod with @debug.Debug::{to_repr}
  60. 60
  61. 61///|
  62. 62pub extend PointCloudSegmentMethod with Eq::{not_equal, equal}
  63. 63
  64. 64///|
  65. 65/// 三维点(轻量级)。
  66. 66/// 三维点(轻量) 3D point (lightweight).
  67. 67#derive(Eq, @debug.Debug)
  68. 68pub(all) struct Point3DLight {
  69. 69 x : Double
  70. 70 y : Double
  71. 71 z : Double
  72. 72}
  73. 73
  74. 74///|
  75. 75pub extend Point3DLight with @debug.Debug::{to_repr}
  76. 76
  77. 77///|
  78. 78pub extend Point3DLight with Eq::{not_equal, equal}
  79. 79
  80. 80///|
  81. 81/// 点云(轻量级)。
  82. 82/// 点 Point cloud (lightweight).
  83. 83#derive(Eq, @debug.Debug)
  84. 84pub(all) struct PointCloud3D {
  85. 85 points : Array[Point3DLight]
  86. 86 normals : Array[Point3DLight] // 法向量(与points对应)
  87. 87}
  88. 88
  89. 89///|
  90. 90pub extend PointCloud3D with @debug.Debug::{to_repr}
  91. 91
  92. 92///|
  93. 93pub extend PointCloud3D with Eq::{not_equal, equal}
  94. 94
  95. 95///|
  96. 96/// 点云配置。
  97. 97/// 点 Point cloud configuration.
  98. 98#derive(Eq, @debug.Debug)
  99. 99pub(all) struct PointCloudConfig {
  100. 100 sample_method : PointCloudSampleMethod
  101. 101 normal_method : NormalEstimationMethod
  102. 102 segment_method : PointCloudSegmentMethod
  103. 103 knn_k : Int32 // K近邻数
  104. 104 voxel_size : Double // 体素大小
  105. 105 cluster_tolerance : Double // 聚类容差
  106. 106 min_cluster_size : Int32 // 最小聚类大小
  107. 107}
  108. 108
  109. 109///|
  110. 110pub extend PointCloudConfig with @debug.Debug::{to_repr}
  111. 111
  112. 112///|
  113. 113pub extend PointCloudConfig with Eq::{not_equal, equal}
  114. 114
  115. 115///|
  116. 116/// 聚类结果。
  117. 117/// 聚类 Cluster result.
  118. 118#derive(Eq, @debug.Debug)
  119. 119pub(all) struct ClusterResult {
  120. 120 clusters : Array[Array[Int32]] // 每个聚类的点索引
  121. 121 cluster_centers : Array[Point3DLight] // 聚类中心
  122. 122}
  123. 123
  124. 124///|
  125. 125pub extend ClusterResult with @debug.Debug::{to_repr}
  126. 126
  127. 127///|
  128. 128pub extend ClusterResult with Eq::{not_equal, equal}
  129. 129
  130. 130///|
  131. 131/// 默认点云配置。
  132. 132/// 描述 Default point cloud configuration.
  133. 133pub fn default_pointcloud_config() -> PointCloudConfig {
  134. 134● {
  135. 135 sample_method: VoxelGridSampling,
  136. 136 normal_method: KNN,
  137. 137 segment_method: EuclideanClustering,
  138. 138 knn_k: 10,
  139. 139 voxel_size: 0.1,
  140. 140 cluster_tolerance: 0.2,
  141. 141 min_cluster_size: 5,
  142. 142 }
  143. 143}
  144. 144
  145. 145///|
  146. 146/// 创建空点云。
  147. 147/// 创建 Create empty point cloud.
  148. 148pub fn create_empty_cloud() -> PointCloud3D {
  149. 149● { points: [], normals: [], }
  150. 150}
  151. 151
  152. 152///|
  153. 153/// 从点数组创建点云。
  154. 154/// 创建 Create point cloud from point array.
  155. 155pub fn create_cloud(points : Array[Point3DLight]) -> PointCloud3D {
  156. 156● let normals : Array[Point3DLight] = []
  157. 157 for _ in points {
  158. 158● normals.push({ x: 0.0, y: 0.0, z: 1.0, })
  159. 159 }
  160. 160 { points, normals, }
  161. 161}
  162. 162
  163. 163///|
  164. 164/// 计算两点距离。
  165. 165/// 计算 Compute distance between two points.
  166. 166fn point_distance(p1 : Point3DLight, p2 : Point3DLight) -> Double {
  167. 167● let dx = p1.x - p2.x
  168. 168 let dy = p1.y - p2.y
  169. 169 let dz = p1.z - p2.z
  170. 170● (dx * dx + dy * dy + dz * dz).sqrt()
  171. 171}
  172. 172
  173. 173///|
  174. 174/// 计算点云质心。
  175. 175/// 计算 Compute point cloud centroid.
  176. 176pub fn compute_centroid(cloud : PointCloud3D) -> Point3DLight {
  177. 177● let n = cloud.points.length()
  178. 178 if n == 0 {
  179. 179● return { x: 0.0, y: 0.0, z: 0.0, }
  180. 180 }
  181. 181 let mut sum_x = 0.0
  182. 182 let mut sum_y = 0.0
  183. 183 let mut sum_z = 0.0
  184. 184 for p in cloud.points {
  185. 185● sum_x = sum_x + p.x
  186. 186 sum_y = sum_y + p.y
  187. 187 sum_z = sum_z + p.z
  188. 188 }
  189. 189 {
  190. 190● x: sum_x / n.to_double(),
  191. 191● y: sum_y / n.to_double(),
  192. 192● z: sum_z / n.to_double(),
  193. 193 }
  194. 194}
  195. 195
  196. 196///|
  197. 197/// 随机采样:按比例随机选取点。
  198. 198/// 描述 Random sampling: select points by ratio.
  199. 199pub fn random_sampling(cloud : PointCloud3D, ratio : Double) -> PointCloud3D {
  200. 200● let n = cloud.points.length()
  201. 201● let target_count = (n.to_double() * ratio).to_int()
  202. 202 if target_count >= n {
  203. 203○ return cloud
  204. 204 }
  205. 205 let step = n / target_count
  206. 206 let sampled_points : Array[Point3DLight] = []
  207. 207 let sampled_normals : Array[Point3DLight] = []
  208. 208 let mut i = 0
  209. 209 while i < n {
  210. 210● sampled_points.push(cloud.points[i])
  211. 211● if i < cloud.normals.length() {
  212. 212● sampled_normals.push(cloud.normals[i])
  213. 213 }
  214. 214 i = i + step
  215. 215 }
  216. 216 { points: sampled_points, normals: sampled_normals, }
  217. 217}
  218. 218
  219. 219///|
  220. 220/// 均匀采样:按固定间隔选取点。
  221. 221/// 描述 Uniform sampling: select points at fixed interval.
  222. 222pub fn uniform_sampling(cloud : PointCloud3D, step : Int32) -> PointCloud3D {
  223. 223● if step <= 1 {
  224. 224● return cloud
  225. 225 }
  226. 226 let sampled_points : Array[Point3DLight] = []
  227. 227 let sampled_normals : Array[Point3DLight] = []
  228. 228● let n = cloud.points.length()
  229. 229 let mut i = 0
  230. 230 while i < n {
  231. 231● sampled_points.push(cloud.points[i])
  232. 232● if i < cloud.normals.length() {
  233. 233● sampled_normals.push(cloud.normals[i])
  234. 234 }
  235. 235 i = i + step
  236. 236 }
  237. 237 { points: sampled_points, normals: sampled_normals, }
  238. 238}
  239. 239
  240. 240///|
  241. 241/// 体素网格下采样:将空间划分为体素,每个体素保留一个代表点。
  242. 242/// 描述 Voxel grid downsampling: divide space into voxels, keep one representative per voxel.
  243. 243pub fn voxel_grid_sampling(
  244. 244 cloud : PointCloud3D,
  245. 245 voxel_size : Double,
  246. 246) -> PointCloud3D {
  247. 247● if voxel_size <= 0.0 {
  248. 248○ return cloud
  249. 249 }
  250. 250● let n = cloud.points.length()
  251. 251 if n == 0 {
  252. 252○ return cloud
  253. 253 }
  254. 254 let mut min_x = cloud.points[0].x
  255. 255 let mut min_y = cloud.points[0].y
  256. 256 let mut min_z = cloud.points[0].z
  257. 257 for p in cloud.points {
  258. 258● if p.x < min_x {
  259. 259○ min_x = p.x
  260. 260 }
  261. 261 if p.y < min_y {
  262. 262○ min_y = p.y
  263. 263 }
  264. 264 if p.z < min_z {
  265. 265○ min_z = p.z
  266. 266 }
  267. 267 }
  268. 268 let voxel_map : Array[Point3DLight] = []
  269. 269 let voxel_keys : Array[Int32] = []
  270. 270 for i in 0..<n {
  271. 271● let p = cloud.points[i]
  272. 272● let vx = ((p.x - min_x) / voxel_size).to_int()
  273. 273● let vy = ((p.y - min_y) / voxel_size).to_int()
  274. 274● let vz = ((p.z - min_z) / voxel_size).to_int()
  275. 275 let key = vx * 73856093 + vy * 19349663 + vz * 83492791
  276. 276 let mut found = false
  277. 277● for j in 0..<voxel_keys.length() {
  278. 278● if voxel_keys[j] == key {
  279. 279● found = true
  280. 280 break
  281. 281 }
  282. 282 }
  283. 283 if !found {
  284. 284● voxel_keys.push(key)
  285. 285● voxel_map.push(p)
  286. 286 }
  287. 287 }
  288. 288 let normals : Array[Point3DLight] = []
  289. 289 for _ in voxel_map {
  290. 290● normals.push({ x: 0.0, y: 0.0, z: 1.0, })
  291. 291 }
  292. 292 { points: voxel_map, normals, }
  293. 293}
  294. 294
  295. 295///|
  296. 296/// 点云采样主流程。
  297. 297/// 点 Point cloud sampling pipeline.
  298. 298pub fn sample_pointcloud(
  299. 299 cloud : PointCloud3D,
  300. 300 config : PointCloudConfig,
  301. 301) -> PointCloud3D {
  302. 302● match config.sample_method {
  303. 303○ RandomSampling => random_sampling(cloud, 0.5)
  304. 304○ UniformSampling => uniform_sampling(cloud, 2)
  305. 305● VoxelGridSampling => voxel_grid_sampling(cloud, config.voxel_size)
  306. 306 }
  307. 307}
  308. 308
  309. 309///|
  310. 310/// K近邻搜索:找到距目标点最近的K个点。
  311. 311/// 描述 K-nearest neighbor search: find K closest points to target.
  312. 312pub fn knn_search(
  313. 313 cloud : PointCloud3D,
  314. 314 target : Point3DLight,
  315. 315 k : Int32,
  316. 316) -> Array[Int32] {
  317. 317● let n = cloud.points.length()
  318. 318 if n == 0 || k <= 0 {
  319. 319○ return []
  320. 320 }
  321. 321 let distances : Array[(Int32, Double)] = []
  322. 322 for i in 0..<n {
  323. 323● distances.push((i, point_distance(cloud.points[i], target)))
  324. 324 }
  325. 325● let sorted = sort_by_distance(distances)
  326. 326 let result : Array[Int32] = []
  327. 327● let count = if k < sorted.length() { k } else { sorted.length() }
  328. 328 for i in 0..<count {
  329. 329● let (idx, _) = sorted[i]
  330. 330● result.push(idx)
  331. 331 }
  332. 332 result
  333. 333}
  334. 334
  335. 335///|
  336. 336/// 按距离排序。
  337. 337/// 排序 Sort by distance.
  338. 338fn sort_by_distance(arr : Array[(Int32, Double)]) -> Array[(Int32, Double)] {
  339. 339● let result = arr.copy()
  340. 340● let n = result.length()
  341. 341 for i in 0..<n {
  342. 342● let mut min_idx = i
  343. 343 for j in (i + 1)..<n {
  344. 344● let (_, d1) = result[min_idx]
  345. 345 let (_, d2) = result[j]
  346. 346 if d2 < d1 {
  347. 347● min_idx = j
  348. 348 }
  349. 349 }
  350. 350 if min_idx != i {
  351. 351● let tmp = result[i]
  352. 352 result[i] = result[min_idx]
  353. 353 result[min_idx] = tmp
  354. 354 }
  355. 355 }
  356. 356 result
  357. 357}
  358. 358
  359. 359///|
  360. 360/// 估计法向量:使用K近邻的协方差矩阵特征向量。
  361. 361/// 描述 Estimate normal vectors: use eigenvector of KNN covariance matrix.
  362. 362pub fn estimate_normals(
  363. 363 cloud : PointCloud3D,
  364. 364 config : PointCloudConfig,
  365. 365) -> PointCloud3D {
  366. 366● let n = cloud.points.length()
  367. 367 if n == 0 {
  368. 368○ return cloud
  369. 369 }
  370. 370 let normals : Array[Point3DLight] = []
  371. 371 for i in 0..<n {
  372. 372● let neighbors = knn_search(cloud, cloud.points[i], config.knn_k)
  373. 373 let mut sum_x = 0.0
  374. 374 let mut sum_y = 0.0
  375. 375 let mut sum_z = 0.0
  376. 376● let count = neighbors.length()
  377. 377 if count == 0 {
  378. 378○ normals.push({ x: 0.0, y: 0.0, z: 1.0, })
  379. 379 continue
  380. 380 }
  381. 381 for idx in neighbors {
  382. 382● sum_x = sum_x + cloud.points[idx].x
  383. 383 sum_y = sum_y + cloud.points[idx].y
  384. 384 sum_z = sum_z + cloud.points[idx].z
  385. 385 }
  386. 386● let cx = sum_x / count.to_double()
  387. 387● let cy = sum_y / count.to_double()
  388. 388● let cz = sum_z / count.to_double()
  389. 389 let mut cxx = 0.0
  390. 390 let mut cyy = 0.0
  391. 391 let mut czz = 0.0
  392. 392 for idx in neighbors {
  393. 393● let dx = cloud.points[idx].x - cx
  394. 394 let dy = cloud.points[idx].y - cy
  395. 395 let dz = cloud.points[idx].z - cz
  396. 396 cxx = cxx + dx * dx
  397. 397 cyy = cyy + dy * dy
  398. 398 czz = czz + dz * dz
  399. 399 }
  400. 400 let nx = cxx
  401. 401 let ny = cyy
  402. 402 let nz = czz
  403. 403● let mag = (nx * nx + ny * ny + nz * nz).sqrt()
  404. 404 if mag > 0.0001 {
  405. 405● normals.push({ x: nx / mag, y: ny / mag, z: nz / mag, })
  406. 406 } else {
  407. 407○ normals.push({ x: 0.0, y: 0.0, z: 1.0, })
  408. 408 }
  409. 409 }
  410. 410 { points: cloud.points, normals, }
  411. 411}
  412. 412
  413. 413///|
  414. 414/// 欧式聚类分割:基于距离的聚类。
  415. 415/// 描述 Euclidean clustering: distance-based clustering.
  416. 416pub fn euclidean_clustering(
  417. 417 cloud : PointCloud3D,
  418. 418 tolerance : Double,
  419. 419 min_cluster_size : Int32,
  420. 420) -> ClusterResult {
  421. 421● let n = cloud.points.length()
  422. 422 if n == 0 {
  423. 423○ return { clusters: [], cluster_centers: [], }
  424. 424 }
  425. 425 let visited : Array[Bool] = []
  426. 426 for _ in 0..<n {
  427. 427● visited.push(false)
  428. 428 }
  429. 429 let clusters : Array[Array[Int32]] = []
  430. 430 for i in 0..<n {
  431. 431● if visited[i] {
  432. 432● continue
  433. 433 }
  434. 434 let cluster : Array[Int32] = []
  435. 435 let queue : Array[Int32] = [i]
  436. 436 visited[i] = true
  437. 437● while queue.length() > 0 {
  438. 438● let curr = queue[queue.length() - 1]
  439. 439● ignore(queue.remove(queue.length() - 1))
  440. 440● cluster.push(curr)
  441. 441 for j in 0..<n {
  442. 442● if !visited[j] &&
  443. 443● point_distance(cloud.points[curr], cloud.points[j]) < tolerance {
  444. 444● visited[j] = true
  445. 445● queue.push(j)
  446. 446 }
  447. 447 }
  448. 448 }
  449. 449● if cluster.length() >= min_cluster_size {
  450. 450● clusters.push(cluster)
  451. 451 }
  452. 452 }
  453. 453 let centers : Array[Point3DLight] = []
  454. 454 for cluster in clusters {
  455. 455● let mut sum_x = 0.0
  456. 456 let mut sum_y = 0.0
  457. 457 let mut sum_z = 0.0
  458. 458 for idx in cluster {
  459. 459● sum_x = sum_x + cloud.points[idx].x
  460. 460 sum_y = sum_y + cloud.points[idx].y
  461. 461 sum_z = sum_z + cloud.points[idx].z
  462. 462 }
  463. 463● let cnt = cluster.length().to_double()
  464. 464● centers.push({ x: sum_x / cnt, y: sum_y / cnt, z: sum_z / cnt, })
  465. 465 }
  466. 466 { clusters, cluster_centers: centers, }
  467. 467}
  468. 468
  469. 469///|
  470. 470/// 平面分割:RANSAC平面拟合。
  471. 471/// 描述 Plane segmentation: RANSAC plane fitting.
  472. 472pub fn plane_segmentation(
  473. 473 cloud : PointCloud3D,
  474. 474 threshold : Double,
  475. 475 max_iterations : Int32,
  476. 476) -> (Point3DLight, Double, Array[Int32]) {
  477. 477● let n = cloud.points.length()
  478. 478 if n < 3 {
  479. 479○ return ({ x: 0.0, y: 0.0, z: 1.0, }, 0.0, [])
  480. 480 }
  481. 481 let mut best_normal = { x: 0.0, y: 0.0, z: 1.0, }
  482. 482 let mut best_d = 0.0
  483. 483 let mut best_inliers : Array[Int32] = []
  484. 484 for iter in 0..<max_iterations {
  485. 485● let i1 = iter % n
  486. 486 let i2 = (iter + n / 3) % n
  487. 487 let i3 = (iter + 2 * n / 3) % n
  488. 488 let p1 = cloud.points[i1]
  489. 489 let p2 = cloud.points[i2]
  490. 490 let p3 = cloud.points[i3]
  491. 491 let v1x = p2.x - p1.x
  492. 492 let v1y = p2.y - p1.y
  493. 493 let v1z = p2.z - p1.z
  494. 494 let v2x = p3.x - p1.x
  495. 495 let v2y = p3.y - p1.y
  496. 496 let v2z = p3.z - p1.z
  497. 497 let nx = v1y * v2z - v1z * v2y
  498. 498 let ny = v1z * v2x - v1x * v2z
  499. 499 let nz = v1x * v2y - v1y * v2x
  500. 500● let mag = (nx * nx + ny * ny + nz * nz).sqrt()
  501. 501 if mag < 0.0001 {
  502. 502● continue
  503. 503 }
  504. 504 let nx = nx / mag
  505. 505 let ny = ny / mag
  506. 506 let nz = nz / mag
  507. 507 let d = -(nx * p1.x + ny * p1.y + nz * p1.z)
  508. 508 let inliers : Array[Int32] = []
  509. 509 for i in 0..<n {
  510. 510● let dist = (nx * cloud.points[i].x +
  511. 511 ny * cloud.points[i].y +
  512. 512 nz * cloud.points[i].z +
  513. 513● d).abs()
  514. 514 if dist < threshold {
  515. 515● inliers.push(i)
  516. 516 }
  517. 517 }
  518. 518● if inliers.length() > best_inliers.length() {
  519. 519● best_normal = { x: nx, y: ny, z: nz, }
  520. 520 best_d = d
  521. 521 best_inliers = inliers
  522. 522 }
  523. 523 }
  524. 524 (best_normal, best_d, best_inliers)
  525. 525}
  526. 526
  527. 527///|
  528. 528/// 点云分割主流程。
  529. 529/// 点 Point cloud segmentation pipeline.
  530. 530pub fn segment_pointcloud(
  531. 531 cloud : PointCloud3D,
  532. 532 config : PointCloudConfig,
  533. 533) -> ClusterResult {
  534. 534● match config.segment_method {
  535. 535 EuclideanClustering =>
  536. 536● euclidean_clustering(
  537. 537 cloud,
  538. 538 config.cluster_tolerance,
  539. 539 config.min_cluster_size,
  540. 540 )
  541. 541 RegionGrowing =>
  542. 542○ euclidean_clustering(
  543. 543 cloud,
  544. 544 config.cluster_tolerance,
  545. 545 config.min_cluster_size,
  546. 546 )
  547. 547○ PlaneSegmentation => {
  548. 548○ let (_, _, inliers) = plane_segmentation(
  549. 549 cloud,
  550. 550 config.cluster_tolerance,
  551. 551 100,
  552. 552 )
  553. 553○ let centers = if inliers.length() > 0 {
  554. 554○ [compute_centroid(cloud)]
  555. 555 } else {
  556. 556○ []
  557. 557 }
  558. 558 { clusters: [inliers], cluster_centers: centers, }
  559. 559 }
  560. 560 }
  561. 561}
  562. 562
  563. 563///|
  564. 564/// 点云处理流水线:采样 → 法向估计 → 分割。
  565. 565/// 点 Point cloud processing pipeline: sample → normal estimation → segmentation.
  566. 566pub fn pointcloud_pipeline(
  567. 567 cloud : PointCloud3D,
  568. 568 config : PointCloudConfig,
  569. 569) -> (PointCloud3D, ClusterResult) {
  570. 570● let sampled = sample_pointcloud(cloud, config)
  571. 571● let with_normals = estimate_normals(sampled, config)
  572. 572● let clusters = segment_pointcloud(with_normals, config)
  573. 573 (with_normals, clusters)
  574. 574}