/
lidar_rooftop_analysis.rs
executable file
·1928 lines (1783 loc) · 82.6 KB
/
lidar_rooftop_analysis.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 10/06/2020
Last Modified: 10/06/2020
License: MIT
*/
use self::na::Vector3;
use whitebox_common::algorithms;
use whitebox_lidar::*;
use crate::na;
use whitebox_common::structures::{DistanceMetric, FixedRadiusSearch3D, Point2D, Point3D, RectangleWithData};
use crate::tools::*;
use whitebox_vector::*;
use kdtree::distance::squared_euclidean;
use kdtree::KdTree;
use num_cpus;
use rand::seq::SliceRandom;
use rstar::RTree;
use std::io::{Error, ErrorKind};
use std::ops::AddAssign;
use std::path;
use std::sync::{mpsc, Arc};
use std::thread;
use std::{env, fs};
const EPSILON: f64 = std::f64::EPSILON;
/// This tool can be used to identify roof segments in a LiDAR point cloud.
///
/// # See Also
/// `ClassifyBuildingsInLidar`, `ClipLidarToPolygon`
pub struct LidarRooftopAnalysis {
name: String,
description: String,
toolbox: String,
parameters: Vec<ToolParameter>,
example_usage: String,
}
impl LidarRooftopAnalysis {
/// public constructor
pub fn new() -> LidarRooftopAnalysis {
let name = "LidarRooftopAnalysis".to_string();
let toolbox = "LiDAR Tools".to_string();
let description = "Identifies roof segments in a LiDAR point cloud.".to_string();
let mut parameters = vec![];
parameters.push(ToolParameter {
name: "Input File".to_owned(),
flags: vec!["-i".to_owned(), "--input".to_owned()],
description: "Input LiDAR file.".to_owned(),
parameter_type: ParameterType::ExistingFile(ParameterFileType::Lidar),
default_value: None,
optional: true,
});
parameters.push(ToolParameter {
name: "Input Building Footprint Polygon File".to_owned(),
flags: vec!["--buildings".to_owned()],
description: "Input vector build footprint polygons file.".to_owned(),
parameter_type: ParameterType::ExistingFile(ParameterFileType::Vector(
VectorGeometryType::Polygon,
)),
default_value: None,
optional: false,
});
// parameters.push(ToolParameter {
// name: "Output LiDAR File".to_owned(),
// flags: vec!["--output_lidar".to_owned()],
// description: "Output LiDAR file.".to_owned(),
// parameter_type: ParameterType::NewFile(ParameterFileType::Lidar),
// default_value: None,
// optional: false,
// });
parameters.push(ToolParameter {
name: "Output Polygon File".to_owned(),
flags: vec!["-o".to_owned(), "--output".to_owned()],
description: "Output vector polygon file.".to_owned(),
parameter_type: ParameterType::NewFile(ParameterFileType::Vector(
VectorGeometryType::Polygon,
)),
default_value: None,
optional: false,
});
parameters.push(ToolParameter {
name: "Search Radius".to_owned(),
flags: vec!["--radius".to_owned()],
description: "Search Radius.".to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("2.0".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Number of Iterations".to_owned(),
flags: vec!["--num_iter".to_owned()],
description: "Number of iterations.".to_owned(),
parameter_type: ParameterType::Integer,
default_value: Some("50".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Number of Sample Points".to_owned(),
flags: vec!["--num_samples".to_owned()],
description: "Number of sample points on which to build the model.".to_owned(),
parameter_type: ParameterType::Integer,
default_value: Some("10".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Inlier Threshold".to_owned(),
flags: vec!["--threshold".to_owned()],
description: "Threshold used to determine inlier points (in elevation units)."
.to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("0.15".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Acceptable Model Size (points)".to_owned(),
flags: vec!["--model_size".to_owned()],
description: "Acceptable model size, in points.".to_owned(),
parameter_type: ParameterType::Integer,
default_value: Some("15".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Maximum Planar Slope (degrees)".to_owned(),
flags: vec!["--max_slope".to_owned()],
description: "Maximum planar slope, in degrees.".to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("65.0".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Normal Difference Threshold (degrees)".to_owned(),
flags: vec!["--norm_diff".to_owned()],
description: "Maximum difference in normal vectors, in degrees.".to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("10.0".to_owned()),
optional: true,
});
// parameters.push(ToolParameter{
// name: "Maximum Elevation Difference Between Points".to_owned(),
// flags: vec!["--maxzdiff".to_owned()],
// description: "Maximum difference in elevation (z units) between neighbouring points of the same segment.".to_owned(),
// parameter_type: ParameterType::Float,
// default_value: Some("1.0".to_owned()),
// optional: true
// });
parameters.push(ToolParameter {
name: "Azimuth (degrees)".to_owned(),
flags: vec!["--azimuth".to_owned()],
description: "Illumination source azimuth, in degrees.".to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("180.0".to_owned()),
optional: true,
});
parameters.push(ToolParameter {
name: "Altitude (degrees)".to_owned(),
flags: vec!["--altitude".to_owned()],
description: "Illumination source altitude in degrees.".to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("30.0".to_owned()),
optional: true,
});
let sep: String = path::MAIN_SEPARATOR.to_string();
let e = format!("{}", env::current_exe().unwrap().display());
let mut parent = env::current_exe().unwrap();
parent.pop();
let p = format!("{}", parent.display());
let mut short_exe = e
.replace(&p, "")
.replace(".exe", "")
.replace(".", "")
.replace(&sep, "");
if e.contains(".exe") {
short_exe += ".exe";
}
let usage = format!(">>.*{0} -r={1} -v --wd=\"*path*to*data*\" -i='data.las' --polygons='buildings.shp' -o='rooftops.shp' --radius=10.0 --num_iter=10 --num_samples=5 --threshold=0.25 --max_slope=70.0", short_exe, name).replace("*", &sep);
LidarRooftopAnalysis {
name: name,
description: description,
toolbox: toolbox,
parameters: parameters,
example_usage: usage,
}
}
}
impl WhiteboxTool for LidarRooftopAnalysis {
fn get_source_file(&self) -> String {
String::from(file!())
}
fn get_tool_name(&self) -> String {
self.name.clone()
}
fn get_tool_description(&self) -> String {
self.description.clone()
}
fn get_tool_parameters(&self) -> String {
match serde_json::to_string(&self.parameters) {
Ok(json_str) => return format!("{{\"parameters\":{}}}", json_str),
Err(err) => return format!("{:?}", err),
}
}
fn get_example_usage(&self) -> String {
self.example_usage.clone()
}
fn get_toolbox(&self) -> String {
self.toolbox.clone()
}
fn run<'a>(
&self,
args: Vec<String>,
working_directory: &'a str,
verbose: bool,
) -> Result<(), Error> {
let mut input_file = String::new();
let mut polygons_file = String::new();
let mut output_file = String::new();
// let mut output_lidar_file = String::new();
let mut search_radius = 2f64;
let mut num_iter = 50;
let mut num_samples = 10;
let mut threshold = 0.15;
let mut acceptable_model_size = 30;
let mut max_slope = 65f64;
let mut max_norm_diff = 2f64;
let mut max_z_diff = 1f64;
let mut azimuth = 180.0f64;
let mut altitude = 30.0f64;
if args.len() == 0 {
return Err(Error::new(
ErrorKind::InvalidInput,
"Tool run with no parameters.",
));
}
for i in 0..args.len() {
let mut arg = args[i].replace("\"", "");
arg = arg.replace("\'", "");
let cmd = arg.split("="); // in case an equals sign was used
let vec = cmd.collect::<Vec<&str>>();
let mut keyval = false;
if vec.len() > 1 {
keyval = true;
}
let flag_val = vec[0].to_lowercase().replace("--", "-");
if flag_val == "-i" || flag_val == "-input" {
input_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-building" || flag_val == "-buildings" {
polygons_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-o" || flag_val == "-output" {
output_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
// } else if flag_val == "-output_lidar" {
// output_lidar_file = if keyval {
// vec[1].to_string()
// } else {
// args[i + 1].to_string()
// };
} else if flag_val == "-radius" {
search_radius = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-num_iter" {
num_iter = if keyval {
vec[1]
.to_string()
.parse::<usize>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<usize>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-num_samples" {
num_samples = if keyval {
vec[1]
.to_string()
.parse::<usize>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<usize>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-threshold" {
threshold = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-model_size" {
acceptable_model_size = if keyval {
vec[1]
.to_string()
.parse::<usize>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<usize>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-max_slope" {
max_slope = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
if max_slope < 5f64 {
max_slope = 5f64;
}
} else if flag_val == "-norm_diff" {
max_norm_diff = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-maxzdiff" {
max_z_diff = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-azimuth" {
if keyval {
azimuth = vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val));
} else {
azimuth = args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val));
}
} else if flag_val == "-altitude" {
if keyval {
altitude = vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val));
} else {
altitude = args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val));
}
}
}
if verbose {
let tool_name = self.get_tool_name();
let welcome_len = format!("* Welcome to {} *", tool_name).len().max(28);
// 28 = length of the 'Powered by' by statement.
println!("{}", "*".repeat(welcome_len));
println!("* Welcome to {} {}*", tool_name, " ".repeat(welcome_len - 15 - tool_name.len()));
println!("* Powered by WhiteboxTools {}*", " ".repeat(welcome_len - 28));
println!("* www.whiteboxgeo.com {}*", " ".repeat(welcome_len - 23));
println!("{}", "*".repeat(welcome_len));
}
let sep: String = path::MAIN_SEPARATOR.to_string();
let mut progress: i32;
let mut old_progress: i32 = -1;
azimuth = (azimuth - 90f64).to_radians();
altitude = altitude.to_radians();
let sin_theta = altitude.sin();
let cos_theta = altitude.cos();
// if !input_file.contains(&sep) && !input_file.contains("/") {
// input_file = format!("{}{}", working_directory, input_file);
// }
if !polygons_file.contains(&sep) && !polygons_file.contains("/") {
polygons_file = format!("{}{}", working_directory, polygons_file);
}
// if !output_file.contains(&sep) && !output_file.contains("/") {
// output_file = format!("{}{}", working_directory, output_file);
// }
// if !output_lidar_file.contains(&sep) && !output_lidar_file.contains("/") {
// output_lidar_file = format!("{}{}", working_directory, output_lidar_file);
// }
if verbose {
println!("Reading data...")
};
if acceptable_model_size < 5 {
acceptable_model_size = 5;
if verbose {
println!("Warning: The --model_size parameter must be at least 5.");
}
}
if num_samples < 5 {
num_samples = 5;
if verbose {
println!("Warning: The --num_samples parameter must be at least 5.");
}
}
let larger_of_two_samples = num_samples.max(acceptable_model_size);
if max_norm_diff < 0f64 {
max_norm_diff = 0f64;
}
if max_norm_diff > 90f64 {
max_norm_diff = 90f64;
}
max_norm_diff = max_norm_diff.to_radians();
let mut inputs = vec![];
if input_file.is_empty() {
if working_directory.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput,
"This tool must be run by specifying either an individual input file or a working directory."));
}
if std::path::Path::new(&working_directory).is_dir() {
for entry in fs::read_dir(working_directory.clone())? {
let s = entry?
.path()
.into_os_string()
.to_str()
.expect("Error reading path string")
.to_string();
if s.to_lowercase().ends_with(".las") {
inputs.push(s);
} else if s.to_lowercase().ends_with(".laz") {
inputs.push(s);
} else if s.to_lowercase().ends_with(".zlidar") {
inputs.push(s);
} else if s.to_lowercase().ends_with(".zip") {
inputs.push(s);
}
}
} else {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("The input directory ({}) is incorrect.", working_directory),
));
}
} else {
if !input_file.contains(path::MAIN_SEPARATOR) && !input_file.contains("/") {
input_file = format!("{}{}", working_directory, input_file);
}
inputs.push(input_file.clone());
if output_file.is_empty() {
output_file = input_file
.clone()
.replace(".las", ".shp")
.replace(".LAS", ".shp")
.replace(".laz", ".shp")
.replace(".zlidar", ".shp");
}
if !output_file.contains(path::MAIN_SEPARATOR) && !output_file.contains("/") {
output_file = format!("{}{}", working_directory, output_file);
}
}
let polygons =
Arc::new(Shapefile::read(&polygons_file).expect("Error reading buildings polygon."));
let num_records = polygons.num_records;
let start = Instant::now();
// make sure the input vector file is of polygon type
if polygons.header.shape_type.base_shape_type() != ShapeType::Polygon {
return Err(Error::new(
ErrorKind::InvalidInput,
"The input vector data must be of polygon base shape type.",
));
}
// place the axis-aligned bounding boxes of each of the polygons into a vector
let mut building_aabb = Vec::with_capacity(num_records);
for record_num in 0..polygons.num_records {
let record = polygons.get_record(record_num);
if record.shape_type != ShapeType::Null {
building_aabb.push(RectangleWithData::new(
record_num,
[record.x_min, record.y_min],
[record.x_max, record.y_max],
));
}
}
let num_buildings = polygons.num_records;
let building_tree = Arc::new(RTree::bulk_load(building_aabb));
let num_files = inputs.len();
if num_files == 0 {
panic!("No input LiDAR files were found");
}
if verbose {
println!("Clipping lidar to building footprints...")
};
// let input = LasFile::new(&inputs[0], "r").expect("Error reading input LiDAR file");
// let mut output_lidar = LasFile::initialize_using_file(&output_lidar_file, &input);
// output_lidar.header.system_id = "EXTRACTION".to_string();
// output_lidar.header.point_format = 2;
// drop(input);
// let mut las_points = vec![];
let mut las_points_transformed: Vec<Point3D> = vec![];
let mut building_num = vec![];
let mut frs: FixedRadiusSearch3D<usize> =
FixedRadiusSearch3D::new(search_radius, DistanceMetric::SquaredEuclidean);
let mut point_num = 0usize;
let mut projection = String::new();
let num_procs = num_cpus::get();
let mut file_num = 0;
for input_file in inputs {
match LasFile::new(&input_file, "r") {
Ok(mut input) => {
if verbose && file_num < 100 {
println!("Clipping: {}", input.get_short_filename());
}
projection = input.get_wkt();
let n_points = input.header.number_of_points as usize;
let input = Arc::new(input);
let (tx, rx) = mpsc::channel();
for tid in 0..num_procs {
let input = input.clone();
let building_tree = building_tree.clone();
let polygons = polygons.clone();
let tx = tx.clone();
thread::spawn(move || {
let mut progress: usize;
let mut old_progress = 1usize;
let mut pd: PointData;
let mut p: Point3D;
let mut record_num: usize;
// let mut record: &ShapefileGeometry;
let mut point_in_poly: bool;
let mut start_point_in_part: usize;
let mut end_point_in_part: usize;
let mut building_points = vec![];
let mut building_rec: usize;
for point_num in
(0..n_points).filter(|point_num| point_num % num_procs == tid)
{
// p = input.get_point_info(point_num);
p = input.get_transformed_coords(point_num);
pd = input[point_num];
if !pd.withheld()
&& !pd.is_classified_noise()
&& pd.is_late_return()
&& (pd.classification() < 2 || pd.classification() > 5)
{
point_in_poly = false;
building_rec = 0usize;
let ret = building_tree
.locate_all_at_point(&[p.x, p.y])
.collect::<Vec<_>>();
for a in 0..ret.len() {
record_num = ret[a].data;
let record = polygons.get_record(record_num);
for part in 0..record.num_parts as usize {
if !record.is_hole(part as i32) {
// not holes
start_point_in_part = record.parts[part] as usize;
end_point_in_part =
if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
if algorithms::point_in_poly(
&Point2D { x: p.x, y: p.y },
&record.points[start_point_in_part
..end_point_in_part + 1],
) {
point_in_poly = true;
building_rec = record_num;
break;
}
}
}
for part in 0..record.num_parts as usize {
if record.is_hole(part as i32) {
// holes
start_point_in_part = record.parts[part] as usize;
end_point_in_part =
if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
if algorithms::point_in_poly(
&Point2D { x: p.x, y: p.y },
&record.points[start_point_in_part
..end_point_in_part + 1],
) {
point_in_poly = false;
break;
}
}
}
}
if point_in_poly {
building_points.push((point_num, building_rec));
}
}
if num_files == 1 && tid == 0 && verbose {
progress =
(100.0_f64 * point_num as f64 / n_points as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
match tx.send(building_points) {
Ok(_) => {} // do nothing
Err(_) => panic!(
"Error performing clipping operation on file: {}.",
input.get_short_filename()
),
};
});
}
let mut point_in_building = vec![false; n_points];
let mut building = vec![0; n_points];
for _ in 0..num_procs {
let in_building_points =
rx.recv().expect("Error receiving data from thread.");
for p in in_building_points {
point_in_building[p.0] = true;
building[p.0] = p.1;
}
}
for p in 0..n_points {
if point_in_building[p] {
// let pr = input.get_record(p);
// let pd = pr.get_point_data();
let xyz = input.get_transformed_coords(p);
// las_points.push(pr);
las_points_transformed.push(xyz);
building_num.push(building[p]);
frs.insert(xyz.x, xyz.y, xyz.z, point_num);
point_num += 1
}
if num_files == 1 && verbose {
progress = (100.0_f64 * p as f64 / n_points as f64) as i32;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
if num_files > 1 && verbose {
file_num += 1;
progress = (100.0_f64 * file_num as f64 / num_files as f64) as i32;
if progress != old_progress {
println!("Progress ({} of {}): {}%", file_num, num_files, progress);
old_progress = progress;
}
}
}
Err(err) => {
if verbose {
println!("Error reading file {}: {}", input_file, err);
}
}
};
}
////////////
// RANSAC //
////////////
if verbose {
println!("Building roof facet models...");
}
let n_points = las_points_transformed.len();
let num_points: f64 = (las_points_transformed.len() - 1) as f64; // used for progress calculation only
if n_points == 0 {
panic!("No LiDAR points were found when clipping to the building footprints. It is possible that the buildings Shapefile is not in the same projection as the LiDAR data. Use LidarInfo to determine.");
}
let frs = Arc::new(frs); // wrap FRS in an Arc
// let las_points = Arc::new(las_points);
let las_points_transformed = Arc::new(las_points_transformed);
let building_num = Arc::new(building_num);
let num_procs = num_cpus::get();
let (tx, rx) = mpsc::channel();
for tid in 0..num_procs {
let frs = frs.clone();
// let las_points = las_points.clone();
let las_points_transformed = las_points_transformed.clone();
let building_num = building_num.clone();
let tx = tx.clone();
thread::spawn(move || {
let mut n: usize;
// let mut p1: PointData;
// let mut p2: PointData;
let mut p1: Point3D;
let mut p2: Point3D;
let mut index: usize;
let mut rng = &mut rand::thread_rng();
let mut model: Plane;
let mut better_model: Plane;
let mut center_point: Vector3<f64>;
let mut rmse: f64;
let mut min_rmse = f64::MAX;
let mut model_contains_center_point: bool;
let mut building_id: usize;
for point_num in (0..n_points).filter(|point_num| point_num % num_procs == tid) {
let mut best_model: Plane = Plane::zero();
// find the best fitting planar model that contains this point
// p1 = input.get_point_info(point_num);
// p1 = las_points[point_num].get_point_data();
p1 = las_points_transformed[point_num];
center_point = Vector3::new(p1.x, p1.y, p1.z);
building_id = building_num[point_num];
let ret = frs.search(p1.x, p1.y, p1.z);
n = ret.len();
let mut points: Vec<Vector3<f64>> = Vec::with_capacity(n);
let mut model_found = false;
let mut model_points: Vec<usize> = Vec::with_capacity(n);
for j in 0..n {
index = ret[j].0;
if building_num[index] == building_id {
// p2 = las_points[index].get_point_data();
p2 = las_points_transformed[index];
points.push(Vector3::new(p2.x, p2.y, p2.z));
}
}
n = points.len();
if n > larger_of_two_samples {
min_rmse = f64::MAX;
let v: Vec<usize> = (0..n).collect();
for _ in 0..num_iter {
// select n random samples.
let samples: Vec<usize> =
v.choose_multiple(&mut rng, num_samples).cloned().collect();
let data: Vec<Vector3<f64>> =
samples.into_iter().map(|a| points[a]).collect();
// get the best-fit plane
model = Plane::from_points(&data);
if model.slope() < max_slope {
let mut inliers: Vec<Vector3<f64>> = Vec::with_capacity(n);
for j in 0..n {
if model.residual(&points[j]) < threshold {
inliers.push(points[j]);
}
}
if inliers.len() >= acceptable_model_size {
better_model = Plane::from_points(&inliers);
rmse = better_model.rmse(&inliers);
model_contains_center_point =
better_model.residual(¢er_point) < threshold;
if rmse < min_rmse && model_contains_center_point {
min_rmse = rmse;
best_model = better_model;
model_found = true;
if inliers.len() == n || min_rmse == 0f64 {
// You can't get any better than that.
break;
}
}
}
}
}
}
if model_found {
for j in 0..n {
index = ret[j].0;
if best_model.residual(&points[j]) <= threshold {
model_points.push(index);
}
}
if model_points.len() < acceptable_model_size {
model_points.clear();
}
}
tx.send((best_model, min_rmse, model_points)).unwrap();
}
});
}
let mut model_rmse = vec![f64::MAX; n_points];
let mut planes = vec![Plane::zero(); n_points];
for i in 0..n_points {
let (model, rmse, model_points) = rx.recv().expect("Error receiving data from thread.");
if rmse < f64::MAX {
for index in model_points {
if rmse < model_rmse[index] {
model_rmse[index] = rmse;
planes[index] = model;
}
}
}
if verbose {
progress = (100.0_f64 * i as f64 / num_points) as i32;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
// ////////////////////////////////////////
// // Perform the segmentation operation //
////////////////////////////////////////
if verbose {
println!("Segmenting the point cloud...");
}
// let mut p: PointData;
// let mut pn: PointData;
let mut p: Point3D;
let mut pn: Point3D;
let mut segment_id = vec![0usize; n_points];
let mut building_id: usize = 0;
let mut building_id_n: usize;
let mut current_segment = 1usize;
let mut point_id: usize;
let mut norm_diff: f64;
let mut height_diff: f64;
let mut index: usize;
let mut solved_points = 0;
let mut stack = vec![];
let mut last_seed = 0;
let mut is_planar: bool;
let mut is_planar_n: bool;
// all non-planar points belong to the same segment
for i in 0..n_points {
if model_rmse[i] == f64::MAX {
segment_id[i] = current_segment;
solved_points += 1;
}
}
current_segment += 1;
// now do a more fulsome search.
while solved_points < n_points {
// Find a seed-point for a segment
for i in last_seed..n_points {
if segment_id[i] == 0 {
// No segment ID has yet been assigned to this point.
// p = las_points[i].get_point_data();
current_segment += 1;
segment_id[i] = current_segment;
building_id = building_num[i];
stack.push(i);
last_seed = i;
break;
}
}
while !stack.is_empty() {
solved_points += 1;
if verbose {
progress = (100f64 * solved_points as f64 / num_points) as i32;
if progress != old_progress {
println!("Segmenting the point cloud: {}%", progress);
old_progress = progress;
}
}
point_id = stack.pop().expect("Error during pop operation.");
is_planar = if model_rmse[point_id] < f64::MAX {
true
} else {
false
};
/* Check the neighbours to see if there are any
points that have similar normal vectors and
heights. */
// p = las_points[point_id].get_point_data();
p = las_points_transformed[point_id];
let ret = frs.search(p.x, p.y, p.z);
for j in 0..ret.len() {
index = ret[j].0;
if segment_id[index] == 0 {
// It hasn't already been placed in a segment.
is_planar_n = if model_rmse[index] < f64::MAX {
true
} else {
false
};
building_id_n = building_num[index];
if is_planar && is_planar_n && building_id == building_id_n {
// pn = las_points[index].get_point_data();
pn = las_points_transformed[index];
height_diff = (pn.z - p.z).abs();
if height_diff < max_z_diff {
// check the norm diff angle
norm_diff = planes[point_id].angle_between(planes[index]);
if norm_diff < max_norm_diff {
segment_id[index] = current_segment;
stack.push(index);
}
}
}
}
}
}
}
/////////////////////////////////////
// Collect segment characteristics //
/////////////////////////////////////
let mut segment_max_elev = vec![0f64; current_segment + 1];
let mut segment_size = vec![0usize; current_segment + 1];
let mut segment_plane = vec![Plane::zero(); current_segment + 1];
let mut segment_points = vec![vec![]; current_segment + 1];
let mut segment_z_vals = vec![vec![]; current_segment + 1];
let mut seg_building_id = vec![0usize; current_segment + 1];
let mut seg_num: usize;
for point_id in 0..n_points {
seg_num = segment_id[point_id];
segment_size[seg_num] += 1;
// p = las_points[point_id].get_point_data();
p = las_points_transformed[point_id];