-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodLAS.cpp
More file actions
1714 lines (1416 loc) · 46.6 KB
/
modLAS.cpp
File metadata and controls
1714 lines (1416 loc) · 46.6 KB
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
#include "LAS.h"
#include "Progress.h"
#include "myomp.h"
#include "SpatialIndex.h"
#include <limits>
#include <boost/geometry.hpp>
using namespace lidR;
LAS::LAS(S4 las, int ncpu)
{
Rcpp::List index = las.slot("index");
this->sensor = index["sensor"];
this->las = las;
DataFrame data = as<DataFrame>(las.slot("data"));
this->X = data["X"];
this->Y = data["Y"];
this->Z = data["Z"];
if (data.containsElementNamed("Intensity"))
this->I = data["Intensity"];
if (data.containsElementNamed("gpstime"))
this->T = data["gpstime"];
this->npoints = X.size();
this->ncpu = ncpu;
this->filter.resize(npoints);
std::fill(filter.begin(), filter.end(), false);
this->skip.resize(npoints);
std::fill(skip.begin(), skip.end(), false);
}
void LAS::new_filter(LogicalVector b)
{
if (b.size() == 1)
std::fill(skip.begin(), skip.end(), b[0]);
else if (b.size() == (int)npoints)
this->skip = Rcpp::as< std::vector<bool> >(b);
else
Rcpp::stop("Internal error in 'new_filter"); // # nocov
}
/*void LAS::apply_filter()
{
LogicalVector keep = wrap(filter);
X = X[keep];
Y = Y[keep];
Z = Z[keep];
if (I.size() == filter.size())
I = I[keep];
npoints = X.size();
filter = std::vector<bool>(npoints);
std::fill(filter.begin(), filter.end(), false);
}*/
/*IntegerVector LAS::index_filter()
{
std::vector<int> index;
for (int i = 0 ; i < npoints ; i++)
{
if (filter[i]) index.push_back(i+1);
}
return Rcpp::wrap(index);
}*/
void LAS::z_smooth(double size, int method, int shape, double sigma)
{
// shape: 1- rectangle 2- circle
// method: 1- average 2- gaussian
double half_res = size / 2;
double twosquaresigma = 2*sigma*sigma;
double twosquaresigmapi = twosquaresigma * M_PI;
NumericVector Zsmooth = clone(Z);
SpatialIndex tree(las);
Progress pb(npoints, "Point cloud smoothing: ");
bool abort = false;
#pragma omp parallel for num_threads(ncpu)
for (unsigned int i = 0 ; i < npoints ; i++)
{
if (abort) continue;
if (pb.check_interrupt()) abort = true;
pb.increment();
std::vector<PointXYZ> pts;
if(shape == 1)
{
Rectangle rect(X[i]-half_res, X[i]+half_res, Y[i]-half_res, Y[i]+half_res);
tree.lookup(rect, pts);
}
else
{
Circle circ(X[i], Y[i], half_res);
tree.lookup(circ, pts);
}
double w = 0;
double ztot = 0;
double wtot = 0;
for(unsigned int j = 0 ; j < pts.size() ; j++)
{
if (method == 1)
{
w = 1;
}
else
{
double dx = X[i] - pts[j].x;
double dy = Y[i] - pts[j].y;
w = 1/twosquaresigmapi * std::exp(-(dx*dx + dy*dy)/twosquaresigma);
}
ztot += w*pts[j].z;
wtot += w;
}
#pragma omp critical
{
Zsmooth[i] = ztot/wtot;
}
}
if (abort) throw Rcpp::internal::InterruptedException();
Z = Zsmooth;
return;
}
void LAS::z_open(double resolution)
{
double half_res = resolution / 2;
NumericVector Z_out(npoints);
SpatialIndex tree(las, skip);
Progress p(2*npoints, "Morphological filter: ");
// Dilate
for (unsigned int i = 0 ; i < npoints ; i++)
{
p.check_abort();
p.update(i);
if (!skip[i]) continue;
std::vector<PointXYZ> pts;
Rectangle rect(X[i]-half_res, X[i]+half_res,Y[i]-half_res, Y[i]+half_res);
tree.lookup(rect, pts);
double min_pt(std::numeric_limits<double>::max());
for(unsigned int j = 0 ; j < pts.size() ; j++)
{
double z = pts[j].z;
if(z < min_pt)
min_pt = z;
}
Z_out[i] = min_pt;
}
NumericVector Z_temp = clone(Z_out);
// erode
for (unsigned int i = 0 ; i < npoints ; i++)
{
p.check_abort();
p.update(i+npoints);
if (!skip[i]) continue;
std::vector<PointXYZ> pts;
Rectangle rect(X[i]-half_res, X[i]+half_res,Y[i]-half_res, Y[i]+half_res);
tree.lookup(rect, pts);
double max_pt(std::numeric_limits<double>::min());
for(unsigned int j = 0 ; j < pts.size() ; j++)
{
double z = Z_temp[pts[j].id];
if(z > max_pt)
max_pt = z;
}
Z_out[i] = max_pt;
}
Z = Z_out;
return;
}
void LAS::i_range_correction(DataFrame flightlines, double Rs, double f)
{
// Coordinates of the sensors
NumericVector x = flightlines["X"];
NumericVector y = flightlines["Y"];
NumericVector z = flightlines["Z"];
NumericVector t = flightlines["gpstime"];
double i;
// Compute the median sensor elevation then average range for this sensor
// elevation. This gives a rough idea of the expected range and allows for
// detecting failure and bad computations
double median_z_sensor = Rcpp::median(z);
double R_control = mean(median_z_sensor - Z);
IntegerVector Inorm(X.size());
Progress pbar(npoints, "Range computation");
// Loop on each point
for (unsigned int k = 0 ; k < npoints ; k++)
{
pbar.increment();
pbar.check_abort();
double R = range(x, y, z, t, k, R_control);
i = I[k] * std::pow((R/Rs),f);
if (i > 65535)
{
Rf_warningcall(R_NilValue, "Normalized intensity does not fit in 16 bits. Value clamped to 2^16.");
i = 65535;
}
Inorm[k] = i;
}
I = Inorm;
return;
}
// x y z t the spatio-temporal coordinates of the sensor
// k the index of the current point
double LAS::range(NumericVector &x, NumericVector &y , NumericVector &z, NumericVector &t, int k, double R_control)
{
// Considering a set of xyzt positions of the the sensor S and an XYZT unique point P we are looking
// to the two sensor positions the closest (temporarily speaking) to the point P. These two points
// must be before and after point P but "before" and "after" may not exist in edge cases
double ti, tf;
int i, f;
// The sensor positions were already sorted by gpstime at R level
// For the input point, find the closest sensor position.
int ind = search_closest(t, T[k]);
// We need two sensor positions to perform an interpolation. The second closest sensor position
// is either the previous or the next one
if (ind == 0)
{
i = 0;
f = 1;
}
else if (ind == x.size()-1)
{
i = x.size()-2;
f = x.size()-1;
}
else
{
if (std::abs(T[k] - t[ind-1]) < std::abs(T[k] - t[ind+1]))
{
i = ind-1;
f = ind;
}
else
{
i = ind;
f = ind+1;
}
}
ti = t[i];
tf = t[f];
// Because of some edge cases such as a single available position for a given flightline
// the retained positions may come from two different flightlines. We must handle this case.
// The sole possibility (AFAIK) for the following to be true is if a flightline has a single
// sensor position (see #608). In this case there is no way to get two positions
if (tf - ti > 30)
{
i = ind;
f = ind;
ti = t[i];
tf = t[f];
}
double r;
if (i == f)
r = 1;
else
r = 1 - (t[f]-T[k])/(t[f]-t[i]);
double dx = X[k] - (x[i] + (x[f] - x[i])*r);
double dy = Y[k] - (y[i] + (y[f] - y[i])*r);
double dz = Z[k] - (z[i] + (z[f] - z[i])*r);
double R = std::sqrt(dx*dx + dy*dy + dz*dz);
if (sensor != TLS && R > 3 * R_control)
{
Rprintf("An high range R has been computed relatively to the expected average range Rm = %.0lf\n", R_control);
Rprintf("Point number %d at (x,y,z,t) = (%.2lf, %.2lf, %.2lf, %.2lf)\n", k+1, X[k], Y[k], Z[k], T[k]);
Rprintf("Matched with sensor between (%.2lf, %.2lf, %.2lf, %.2lf) and (%.2lf, %.2lf, %.2lf, %.2lf)\n", x[i], y[i], z[i], t[i], x[f], y[f], z[f], t[f]);
Rprintf("The range computed was R = %.2lf\n", R);
Rprintf("Check the correctness of the sensor positions and the correctness of the gpstime either in the point cloud or in the sensor positions.\n");
throw Rcpp::exception("Unrealistic range: see message above", false);
}
return R;
}
NumericVector LAS::compute_range(DataFrame flightlines)
{
// Coordinates of the sensors
NumericVector x = flightlines["X"];
NumericVector y = flightlines["Y"];
NumericVector z = flightlines["Z"];
NumericVector t = flightlines["gpstime"];
// Compute the median sensor elevation then average range for this sensor
// elevation. This gives a rough idea of the expected range and allows for
// detecting failure and bad computations
double median_z_sensor = Rcpp::median(z);
double R_control = mean(median_z_sensor - Z);
NumericVector R(npoints);
Progress pbar(npoints, "Range computation");
// Loop on each point
for (unsigned int k = 0 ; k < npoints ; k++)
{
pbar.increment();
pbar.check_abort();
R[k] = range(x, y, z, t, k, R_control);
}
return R;
}
void LAS::filter_local_maxima(NumericVector ws, double min_height, bool circular)
{
bool abort = false;
bool vws = ws.length() > 1;
SpatialIndex tree(las);
Progress pb(npoints, "Local maximum filter: ");
#pragma omp parallel for num_threads(ncpu)
for (unsigned int i = 0 ; i < npoints ; i++)
{
if (abort) continue;
if (pb.check_interrupt()) abort = true;
pb.increment();
double hws = (vws) ? ws[i]/2 : ws[0]/2;
if (Z[i] < min_height)
continue;
// Get the points within a windows centered on the current point
std::vector<PointXYZ> pts;
if(!circular)
{
Rectangle rect(X[i]-hws, X[i]+hws, Y[i]-hws, Y[i]+hws);
tree.lookup(rect, pts);
}
else
{
Circle circ(X[i], Y[i], hws);
tree.lookup(circ, pts);
}
// Initialize the highest point using the central point
PointXYZ p(X[i], Y[i], Z[i], i);
double zmax = Z[i];
bool is_lm = true;
// Search if one is higher
for (auto pt : pts)
{
double z = pt.z;
// Found one higher, it is not a LM
if(z > zmax)
{
is_lm = false;
break;
}
// Found one equal. If this one was already tagged LM we can't have two lm
// The first tagged has the precedence
if (z == zmax && filter[pt.id])
{
is_lm = false;
break;
}
}
#pragma omp critical
{
filter[i] = is_lm;
}
}
if (abort) throw Rcpp::internal::InterruptedException();
return;
}
void LAS::filter_local_maxima(NumericVector ws)
{
bool abort = false;
int mode;
double radius = 0;
double hwidth = 0;
double hheight = 0;
double orientation = 0;
if (ws.length() == 1)
{
mode = 1; // circular windows
radius = ws[0]/2;
}
else if (ws.length() == 2)
{
mode = 2; // rectangular windows
hwidth = ws[0]/2;
hheight = ws[1]/2;
}
else if (ws.length() == 3)
{
mode = 3; // rectangular oriented windows
hwidth = ws[0]/2;
hheight = ws[1]/2;
orientation = ws[2];
}
else
Rcpp::stop("C++ unexpected internal error in 'filter_local_maxima': invalid windows."); // # nocov
SpatialIndex tree(las, skip);
Progress pb(npoints, "Local maximum filter: ");
#pragma omp parallel for num_threads(ncpu)
for (unsigned int i = 0 ; i < npoints ; i++)
{
if (abort) continue;
if (pb.check_interrupt()) abort = true;
pb.increment();
if (!skip[i]) continue;
// Get the points within a windows centred on the current point
std::vector<PointXYZ> pts;
switch(mode)
{
case 1: {
Circle circ(X[i], Y[i], radius);
tree.lookup(circ, pts);
break;
}
case 2: {
Rectangle rect(X[i] - hwidth, X[i] + hwidth, Y[i] - hheight, Y[i] + hheight);
tree.lookup(rect, pts);
break;
}
case 3: {
double hwidth = ws[0]/2;
double hheight = ws[1]/2;
double orientation = ws[2];
OrientedRectangle orect(X[i] - hwidth, X[i] + hwidth, Y[i] - hheight, Y[i] + hheight, orientation);
tree.lookup(orect, pts);
break;
}
}
// Get the highest Z in the windows
double Zmax = std::numeric_limits<double>::min();
PointXYZ p = pts[0];
for (unsigned int j = 0 ; j < pts.size() ; j++)
{
if(pts[j].z > Zmax)
{
p = pts[j];
Zmax = Z[p.id];
}
}
// The central pixel is the highest, it is a LM
#pragma omp critical
{
if (Z[i] == Zmax && X[i] == p.x && Y[i] == p.y)
filter[i] = true;
}
}
if (abort) throw Rcpp::internal::InterruptedException();
return;
}
void LAS::filter_with_grid(List layout, bool max)
{
int ncols = layout["ncol"];
int nrows = layout["nrow"];
double xmin = layout["xmin"];
double xmax = layout["xmax"];
double ymin = layout["ymin"];
double ymax = layout["ymax"];
double xres = (xmax - xmin) / ncols;
double yres = (ymax - ymin) / nrows;
int limit = (max) ? std::numeric_limits<int>::min() : std::numeric_limits<int>::max();
std::vector<int> output(ncols*nrows);
std::fill(output.begin(), output.end(), limit);
for (unsigned int i = 0 ; i < npoints ; i++)
{
if (skip[i]) continue;
double x = X[i];
double y = Y[i];
double z = Z[i];
int col = std::floor((x - xmin) / xres);
int row = std::floor((ymax - y) / yres);
if (y == ymin) row = nrows-1;
if (x == xmax) col = ncols-1;
if (row < 0 || row >= nrows || col < 0 || col >= ncols)
Rcpp::stop("C++ unexpected internal error in 'filter_with_grid': point out of raster."); // # nocov
int cell = row * ncols + col;
if (output[cell] == limit)
{
output[cell] = i;
}
else
{
double zref = Z[output[cell]];
if (max) {
if (zref < z) output[cell] = i;
} else {
if (zref > z) output[cell] = i;
}
}
}
for (unsigned int i = 0 ; i < output.size() ; i++)
{
if (output[i] != limit)
filter[output[i]] = true;
}
return;
}
IntegerVector LAS::find_polygon_ids(CharacterVector wkts)
{
typedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> Point;
typedef boost::geometry::model::polygon<Point> Polygon;
typedef boost::geometry::model::multi_polygon<Polygon> MultiPolygon;
typedef boost::geometry::model::box<Point> Bbox;
SpatialIndex tree(las);
IntegerVector poly_id(X.size());
std::fill(poly_id.begin(), poly_id.end(), NA_INTEGER);
for (unsigned int j = 0 ; j < wkts.size() ; j++)
{
bool is_in_polygon = false;
std::string wkt = as<std::string>(wkts[j]);
if (wkt.find("MULTIPOLYGON") != std::string::npos)
{
Point p;
Bbox bbox;
MultiPolygon polygons;
boost::geometry::read_wkt(wkt, polygons);
boost::geometry::envelope(polygons, bbox);
double min_x = bbox.min_corner().get<0>();
double min_y = bbox.min_corner().get<1>();
double max_x = bbox.max_corner().get<0>();
double max_y = bbox.max_corner().get<1>();
lidR::Rectangle rect(min_x, max_x, min_y, max_y);
std::vector<PointXYZ> pts;
tree.lookup(rect, pts);
for(unsigned int i = 0 ; i < pts.size() ; i++)
{
p.set<0>(pts[i].x);
p.set<1>(pts[i].y);
if (boost::geometry::covered_by(p, polygons))
poly_id[pts[i].id] = j;
}
}
else if (wkt.find("POLYGON") != std::string::npos)
{
Point p;
Bbox bbox;
Polygon polygon;
boost::geometry::read_wkt(wkt, polygon);
boost::geometry::envelope(polygon, bbox);
double min_x = bbox.min_corner().get<0>();
double min_y = bbox.min_corner().get<1>();
double max_x = bbox.max_corner().get<0>();
double max_y = bbox.max_corner().get<1>();
lidR::Rectangle rect(min_x, max_x, min_y, max_y);
std::vector<PointXYZ> pts;
tree.lookup(rect, pts);
for(unsigned int i = 0 ; i < pts.size() ; i++)
{
p.set<0>(pts[i].x);
p.set<1>(pts[i].y);
if (boost::geometry::covered_by(p, polygon))
poly_id[pts[i].id] = j;
}
}
else
Rcpp::stop("Unexpected error in point_in_polygon: WKT is not a POLYGON or MULTIPOLYGON"); // # nocov
}
return poly_id;
}
void LAS::filter_shape(int method, NumericVector th, int k)
{
Progress pb(npoints, "Eigenvalues computation: ");
bool abort = false;
SpatialIndex qtree(las, skip);
bool (*predicate)(arma::vec&, arma::mat&, NumericVector&);
switch(method)
{
case 1: predicate = &LAS::coplanar; break;
case 2: predicate = &LAS::hcoplanar; break;
case 3: predicate = &LAS::colinear; break;
case 4: predicate = &LAS::hcolinear; break;
case 5: predicate = &LAS::vcolinear; break;
default: Rcpp::stop("Internal error in LAS::filter_shape: invalid method") ; break; // # nocov
}
#pragma omp parallel for num_threads(ncpu)
for (unsigned int i = 0 ; i < npoints ; i++)
{
if (abort) continue;
if (pb.check_interrupt()) abort = true; // No data race here because only thread 0 can actually write
pb.increment();
if (!skip[i]) continue;
arma::mat A(k,3);
arma::mat coeff; // Principle component matrix
arma::mat score;
arma::vec latent; // Eigenvalues in descending order
PointXYZ p(X[i], Y[i], Z[i]);
std::vector<PointXYZ> pts;
qtree.knn(p, k, pts);
for (unsigned int j = 0 ; j < pts.size() ; j++)
{
A(j,0) = pts[j].x;
A(j,1) = pts[j].y;
A(j,2) = pts[j].z;
}
arma::princomp(coeff, score, latent, A);
#pragma omp critical
{
filter[i] = predicate(latent, coeff, th);
}
}
if (abort) throw Rcpp::internal::InterruptedException();
return;
}
void LAS::filter_progressive_morphology(NumericVector ws, NumericVector th)
{
if (ws.size() != th.size())
Rcpp::stop("Internal error in 'filter_progressive_morphology'"); // # nocov
for (int i = 0 ; i < ws.size() ; i++)
{
NumericVector oldZ = clone(Z);
z_open(ws[i]);
for (unsigned int j = 0 ; j < npoints ; j++)
{
if (!skip[j]) continue;
skip[j] = (oldZ[j] - Z[j]) < th[i];
}
}
filter = skip;
return;
}
void LAS::filter_isolated_voxel(double res, unsigned int isolated)
{
double xmin = min(X);
double ymin = min(Y);
double zmin = min(Z);
double xmax = max(X);
double ymax = max(Y);
double zmax = max(Z);
unsigned int width = std::floor((xmax - xmin) / res);
unsigned int height = std::floor((ymax - ymin) / res);
//unsigned int depth = std::floor((zmax - zmin) / res);
// Stores for a given voxel the number of point in its 27 voxels neighbourhood
std::unordered_map<unsigned int, unsigned int> dynamic_registry;
for (unsigned int n = 0 ; n < npoints ; n++)
{
int nx = std::floor((X[n] - xmin) / res);
int ny = std::floor((Y[n] - ymin) / res);
int nz = std::floor((Z[n] - zmin) / res);
// Add one in the 27 neighbouring voxel of this point
for (int i : {-1,0,1})
{
for (int j : {-1,0,1})
{
for (int k : {-1,0,1})
{
if (!(i == 0 && j == 0 && k == 0))
{
unsigned int key = (nx+i) + (ny+j)*width + (nz+k)*width*height;
dynamic_registry.insert({key, 0});
dynamic_registry[key]++;
}
}
}
}
}
// Loop again through each point.
// Check if the number of points in its neighbourhood is above the threshold
for (unsigned int n = 0 ; n < npoints ; n++)
{
int nx = std::floor((X[n] - xmin) / res);
int ny = std::floor((Y[n] - ymin) / res);
int nz = std::floor((Z[n] - zmin) / res);
unsigned int key = nx + ny*width + nz*width*height;
filter[n] = dynamic_registry[key] <= isolated;
}
return;
}
IntegerVector LAS::segment_snags(NumericVector neigh_radii, double low_int_thrsh, double uppr_int_thrsh, int pt_den_req, NumericMatrix BBPRthrsh_mat)
{
NumericVector BBPr_sph(npoints); // vector to store the Branch-Bole point ratio (BBPr) for the sphere neighborhood object
IntegerVector ptDen_sph(npoints); // vector to store the the sphere neighborhood point density for each focal point
NumericVector meanBBPr_sph(npoints); // vector to store the mean BBPr for each focal point in its corresponding sphere neighborhood
NumericVector BBPr_smcyl(npoints); // BBPr for the small cylinder neighborhood (which only includes points above focal point)
IntegerVector ptDen_smcyl(npoints); // the small cylinder neighborhood point density for each focal point
NumericVector meanBBPr_smcyl(npoints); // the mean BBPr for each focal point in its corresponding small cylinder neighborhood
NumericVector BBPr_bigcyl(npoints); // BBPr for the big cylinder neighborhood
IntegerVector ptDen_bigcyl(npoints); // the big cylinder neighborhood point density for each focal point
NumericVector meanBBPr_bigcyl(npoints); // the mean BBPr for each focal point in its corresponding big cylinder neighborhood
SpatialIndex qtree(las); // the SpatialIndex for the las object
// Step 1 - First we have to build neighborhood objects (sphere, small and large cylinders) around each focal point and get
// the BBPr counts, then we have to calculate the actual ratio of BBPr to neighborhood points for each focal point
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#pragma omp parallel for num_threads(ncpu)
for (unsigned int i = 0 ; i < npoints ; i++)
{
double BBPr_cnt = 0; // the count of BBPr points (based on thresholds) in the neighborhood
// Step 1.a Sphere neighborhood
// ----------------------------
std::vector<PointXYZ> sphpts; // creation of an STL container of points for the sphere neighborhood object
Sphere sphere(X[i], Y[i], Z[i], neigh_radii[0]); // creation of a sphere object
qtree.lookup(sphere, sphpts); // lookup the points in the sphere neighborhood
ptDen_sph[i] = sphpts.size(); // count the points in the sphere neighborhood
BBPr_cnt = 0;
for (unsigned int j = 0 ; j < sphpts.size() ; j++)
{
if (I[sphpts[j].id] <= low_int_thrsh || I[sphpts[j].id] >= uppr_int_thrsh)
BBPr_cnt++;
}
#pragma omp critical
{
BBPr_sph[i] = BBPr_cnt/sphpts.size(); // Ratio of BBPr points in the neighborhood
}
// Step 1.b Small cylinder neighborhood
// ------------------------------------
std::vector<PointXYZ> smcylpts; // creation of an STL container of points for the small cylinder neighborhood object
Circle smcircle(X[i], Y[i], neigh_radii[1]); // creation of a small cylinder object
qtree.lookup(smcircle, smcylpts); // lookup the points in the small cylinder neighborhood
BBPr_cnt = 0;
double ptZ = Z[i]; // the height of the focal point (lower end of the small cylinder)
for (unsigned int j = 0 ; j < smcylpts.size() ; j++)
{
if (smcylpts[j].z >= ptZ)
{
ptDen_smcyl[i]++;
if (I[smcylpts[j].id] <= low_int_thrsh || I[smcylpts[j].id] >= uppr_int_thrsh)
BBPr_cnt++;
}
}
#pragma omp critical
{
BBPr_smcyl[i] = BBPr_cnt/ptDen_smcyl[i]; // Ratio of BBPr points in the neighborhood
}
// Step 1.c Big cylinder neighborhood
// ----------------------------------
std::vector<PointXYZ> bigcylpts; // creation of an STL container of points for the big cylinder neighborhood object
Circle bigcircle(X[i], Y[i], neigh_radii[2]); // creation of a big cylinder object
qtree.lookup(bigcircle, bigcylpts); // lookup the points in the big cylinder neighborhood
ptDen_bigcyl[i] = bigcylpts.size(); // get the point density in the big cylinder neighborhood
BBPr_cnt = 0;
for (unsigned int j = 0; j < bigcylpts.size(); j++)
{
if (I[bigcylpts[j].id] <= low_int_thrsh || I[bigcylpts[j].id] >= uppr_int_thrsh)
BBPr_cnt++;
}
#pragma omp critical
{
BBPr_bigcyl[i] = BBPr_cnt/bigcylpts.size(); // Ratio of BBPr points in the neighborhood
}
}
// Step 2 - Next we have to calculate he mean BBPr value for points in the neighborhood object for each focal point
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#pragma omp parallel for num_threads(ncpu)
for (unsigned int i = 0 ; i < npoints ; i++)
{
double sum_of_elements = 0; // sum the elements in the neighborhood
// Step 2.a Sphere neighborhood
// ----------------------------
std::vector<PointXYZ> sphpts;
Sphere sphere(X[i], Y[i], Z[i], neigh_radii[0]);
qtree.lookup(sphere, sphpts);
sum_of_elements = 0;
for (unsigned int j = 0; j < sphpts.size(); j++)
{
sum_of_elements += BBPr_sph[sphpts[j].id];
}
#pragma omp critical
{
meanBBPr_sph[i] = sum_of_elements/ptDen_sph[i]; // calculate the mean
}
// Step 2.b Small cylinder neighborhood
// ------------------------------------
std::vector<PointXYZ> smcylpts;
Circle smcircle(X[i], Y[i], neigh_radii[1]);
qtree.lookup(smcircle, smcylpts);
sum_of_elements = 0;
double ptZ = Z[i]; // the height of he focal point (lower end of the small cylinder)
for (unsigned int j = 0 ; j < smcylpts.size() ; j++)
{
if (smcylpts[j].z >= ptZ)
sum_of_elements += BBPr_smcyl[smcylpts[j].id];
}
#pragma omp critical
{
meanBBPr_smcyl[i] = sum_of_elements/ptDen_smcyl[i]; // calculate the mean
}
// Step 2.c Big cylinder neighborhood
// ----------------------------------
std::vector<PointXYZ> bigcylpts;
Circle bigcircle(X[i], Y[i], neigh_radii[2]);
qtree.lookup(bigcircle, bigcylpts);
sum_of_elements = 0;
for (unsigned int j = 0 ; j < bigcylpts.size() ; j++)
{
sum_of_elements += BBPr_bigcyl[bigcylpts[j].id];
}
#pragma omp critical
{
meanBBPr_bigcyl[i] = sum_of_elements/ptDen_bigcyl[i]; // calculate the mean
}
}
// Step 3 - Finally classify each point based on point density requirements and mean BBPr values from on the lookup table
// in Wing et al 2015 - Table 2 - pg. 172 - here, the values supplied/specified by user in BBPRthrsh_mat
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
IntegerVector output(npoints); // vector to store the snag (or tree) classification values
for(unsigned int i = 0 ; i < npoints ; i++)
{
if (ptDen_sph[i] >= pt_den_req &&
meanBBPr_sph[i] >= BBPRthrsh_mat(0,0) &&
ptDen_smcyl[i] >= pt_den_req &&
meanBBPr_smcyl[i] >= BBPRthrsh_mat(1,0) &&
ptDen_bigcyl[i] >= pt_den_req &&
meanBBPr_bigcyl[i] >= BBPRthrsh_mat(2,0))
{
output[i] = 1; // General snag class
}
else if (ptDen_sph[i] >= 2 &&
ptDen_sph[i] <= pt_den_req &&
meanBBPr_sph[i] >= BBPRthrsh_mat(0,1) &&
ptDen_smcyl[i] >= 2 &&
ptDen_smcyl[i] <= pt_den_req &&
meanBBPr_smcyl[i] >= BBPRthrsh_mat(1,1) &&
ptDen_bigcyl[i] >= 2 &&
ptDen_bigcyl[i] <= pt_den_req &&
meanBBPr_bigcyl[i] >= BBPRthrsh_mat(2,1))
{
output[i] = 2; // Small snag class
}
else if (ptDen_sph[i] >= pt_den_req &&
meanBBPr_sph[i] >= BBPRthrsh_mat(0,2) &&
ptDen_smcyl[i] >= pt_den_req &&
meanBBPr_smcyl[i] >= BBPRthrsh_mat(1,2) &&
ptDen_bigcyl[i] >= pt_den_req*7 &&
meanBBPr_bigcyl[i] >= BBPRthrsh_mat(2,2))
{
output[i] = 3; // Live crown edge snag class
}
else if (ptDen_sph[i] >= pt_den_req &&
meanBBPr_sph[i] >= BBPRthrsh_mat(0,3) &&
ptDen_smcyl[i] >= pt_den_req &&
meanBBPr_smcyl[i] >= BBPRthrsh_mat(1,3) &&
ptDen_bigcyl[i] >= pt_den_req*15 &&
meanBBPr_bigcyl[i] >= BBPRthrsh_mat(2,3))
{
output[i] = 4; // High canopy cover snag class
}
else
{
output[i] = 0; // Remaining points assigned to live tree class
}
}
return(output);
}
IntegerVector LAS::segment_trees(double dt1, double dt2, double Zu, double R, double th_tree, double radius)
{
double xmin = min(X);
double ymin = min(Y);
unsigned int ni = npoints; // Number of points
unsigned int n = ni; // Number of remaining points
unsigned int k = 1; // Current tree ID