-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
LAS.cpp
1426 lines (1178 loc) · 40.3 KB
/
LAS.cpp
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 <boost/geometry.hpp>
#include <limits>
//#include "QuadTree.h"
#include "GridPartition.h"
#include "Progress.h"
#include "myomp.h"
typedef GridPartition SpatialIndex;
LAS::LAS(S4 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 = 1;
this->filter.resize(npoints);
std::fill(filter.begin(), filter.end(), false);
}
LAS::LAS(S4 las, int ncpu)
{
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"];
this->npoints = X.size();
this->ncpu = ncpu;
this->filter.resize(npoints);
std::fill(filter.begin(), filter.end(), false);
}
LAS::~LAS()
{
}
void LAS::new_filter(LogicalVector b)
{
if (b.size() == 1)
std::fill(filter.begin(), filter.end(), b[0]);
else if (b.size() == (int)npoints)
this->filter = 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(X,Y);
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<Point*> 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*Z[pts[j]->id];
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(X, Y, filter);
Progress p(2*npoints, "Morphological filter: ");
// Dilate
for (unsigned int i = 0 ; i < npoints ; i++)
{
p.check_abort();
p.update(i);
if (!filter[i]) continue;
std::vector<Point*> 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 = Z[pts[j]->id];
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 (!filter[i]) continue;
std::vector<Point*> 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;
}
double LAS::range(NumericVector &x, NumericVector &y , NumericVector &z, NumericVector &t, int k, double R_control)
{
NumericVector::iterator it;
double dx, dy, dz, r, R;
double i;
int j = 0;
// The sensor positions were already sorted a R level
// For each point find the first element that is not less than the time t of the points
// This give the closest position of the sensor after (t1) the aqcuisition of the points (t)
it = std::lower_bound(t.begin(), t.end(), T[k]);
// We now need the sensor position before (t0) the aqcuisition.
// If the sensor position is the first one: no sensor position exists before this one
// thus no interpolation possible. We use the next one.
if (it == t.begin())
{
j = 1;
}
// If the sensor position not found: no sensor position exists after this one
// thus no interpolation possible. We use the last one.
else if (it == t.end())
{
j = x.size() - 1;
}
// If t1-t0 is too big it is two differents flightlines. We must hold this case by chosing
// if we use the previous point or this one.
else if (std::abs(*it - *(it-1)) > 30)
{
// If t is closer to the previous one
if (std::abs(T[k] - *(it-1)) < std::abs(T[k] - *(it+1)))
j = it - t.begin() - 1;
else
j = it - t.begin() + 1;
}
// General case with t1 > t > t0. We have a sensor position after the aquisition of the point
// and it is not the first one. So we necessarily have a previous one. We can make the
// interpolation
else
{
j = it - t.begin();
}
if (j >= x.size()) throw Rcpp::exception("Internal error: access to coordinates beyond the limits of the array. Please report this bug.", false);
if (j <= 0) throw Rcpp::exception("Internal error: access to coordinates below 0 in the array. Please report this bug.", false);
r = 1 - (t[j]-T[k])/(t[j]-t[j-1]);
dx = X[k] - (x[j-1] + (x[j] - x[j-1])*r);
dy = Y[k] - (y[j-1] + (y[j] - y[j-1])*r);
dz = Z[k] - (z[j-1] + (z[j] - z[j-1])*r);
R = std::sqrt(dx*dx + dy*dy + dz*dz);
if (R > 3 * R_control)
{
REprintf("An high range R has been computed relatively to the expected average range Rm = %.0lf\n", R_control);
REprintf("Point number %d at (x,y,z,t) = (%.2lf, %.2lf, %.2lf, %.2lf)\n", k+1, X[k], Y[k], Z[k], T[k]);
REprintf("Matched with sensor between (%.2lf, %.2lf, %.2lf, %.2lf) and (%.2lf, %.2lf, %.2lf, %.2lf)\n", x[j-1], y[j-1], z[j-1], t[j-1], x[j], y[j], z[j], t[j]);
REprintf("The range computed was R = %.2lf\n", R, dx, dy, dz, t[j]);
REprintf("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(X,Y);
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<Point*> 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);
}
// Get the highest Z in the windows
double Zmax = std::numeric_limits<double>::min();
Point* p = pts[0];
for (unsigned int j = 0 ; j < pts.size() ; j++)
{
if(Z[pts[j]->id] > 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_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(X,Y);
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();
// Get the points within a windows centered on the current point
std::vector<Point*> 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();
Point* p = pts[0];
for (unsigned int j = 0 ; j < pts.size() ; j++)
{
if(Z[pts[j]->id] > 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(S4 layout)
{
S4 extent = layout.slot("extent");
int ncols = layout.slot("ncols");
int nrows = layout.slot("nrows");
double xmin = extent.slot("xmin");
double xmax = extent.slot("xmax");
double ymin = extent.slot("ymin");
double ymax = extent.slot("ymax");
double xres = (xmax - xmin) / ncols;
double yres = (ymax - ymin) / nrows;
std::vector<int> output(ncols*nrows);
std::fill(output.begin(), output.end(), std::numeric_limits<int>::min());
for (unsigned int i = 0 ; i < npoints ; i++)
{
if (filter[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] == std::numeric_limits<int>::min())
{
output[cell] = i;
}
else
{
double zref = Z[output[cell]];
if (zref < z) output[cell] = i;
}
}
for (unsigned int i = 0 ; i < output.size() ; i++)
{
if (output[i] > std::numeric_limits<int>::min())
filter[output[i]] = true;
}
return;
}
void LAS::filter_in_polygon(std::string wkt)
{
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;
if (wkt.find("MULTIPOLYGON") != std::string::npos)
{
Point p;
Bbox bbox;
MultiPolygon polygons;
boost::geometry::read_wkt(wkt, polygons);
boost::geometry::envelope(polygons, bbox);
#pragma omp parallel for num_threads(ncpu)
for(unsigned int i = 0 ; i < npoints ; i++)
{
if (filter[i]) continue;
Point p;
p.set<0>(X[i]);
p.set<1>(Y[i]);
bool isin = false;
if (boost::geometry::covered_by(p, bbox))
{
if (boost::geometry::covered_by(p, polygons))
isin = true;
}
#pragma omp critical
{
filter[i] = isin;
}
}
}
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);
#pragma omp parallel for num_threads(ncpu)
for(unsigned int i = 0 ; i < npoints ; i++)
{
if (filter[i]) continue;
Point p;
p.set<0>(X[i]);
p.set<1>(Y[i]);
bool isin = false;
if (boost::geometry::covered_by(p, bbox))
{
if (boost::geometry::covered_by(p, polygon))
isin = true;
}
#pragma omp critical
{
filter[i] = isin;
}
}
}
else
Rcpp::stop("Unexpected error in point in polygon: WKT is not a POLYGON or MULTIPOLYGON"); // # nocov
return;
}
void LAS::filter_shape(int method, NumericVector th, int k)
{
Progress pb(npoints, "Eigenvalues computation: ");
bool abort = false;
SpatialIndex qtree(X,Y,Z, filter);
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;
}
#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 (!filter[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 (!filter[j]) continue;
filter[j] = (oldZ[j] - Z[j]) < th[i];
}
}
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(X,Y,Z); // 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<Point*> 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 (Z[smcylpts[j]->id] >= 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<Point*> 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<Point*> 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 (Z[smcylpts[j]->id]>=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<Point*> 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
// The ID of each point (returned object)
IntegerVector idtree(ni);
std::fill(idtree.begin(), idtree.end(), NA_INTEGER);
// Square distance to speed up computation (dont need sqrt)
radius = radius * radius;
dt1 = dt1 * dt1;
dt2 = dt2 * dt2;
/* =====================
* LI ET AL ALGORITHHM *
======================*/
// Li, W., Guo, Q., Jakubowski, M. K., & Kelly, M. (2012). A New Method for Segmenting Individual
// Trees from the Lidar Point Cloud. Photogrammetric Engineering & Remote Sensing, 78(1), 75–84.
// https://doi.org/10.14358/PERS.78.1.75
// Find if a point is a local maxima within an R windows
LogicalVector is_lm;
if (R > 0)
{
filter_local_maxima(NumericVector::create(R), 0, true);
is_lm = Rcpp::wrap(filter);
}
else
{
is_lm = LogicalVector(ni);
std::fill(is_lm.begin(), is_lm.end(), true);
}
// A progress bar and abort options
Progress p(ni, "Tree segmentation: ");
// U the points to be segmented (see Li et al. page 78)
std::vector<PointXYZ*> U(ni);
for (unsigned int i = 0 ; i < ni ; ++i)
U[i] = new PointXYZ(X[i], Y[i], Z[i], i);
// N and P groups (see Li et al. page 78)
std::vector<PointXYZ*> P,N;
P.reserve(100);
N.reserve(100);
// A dummy point out of the dataset (see Li et al. page 79)
PointXYZ* dummy = new PointXYZ(xmin-100,ymin-100,0,-1);
// Z-sort the point cloud U
std::sort(U.begin(), U.end(), ZSort<PointXYZ>());
while(n > 0)
{
PointXYZ* u = U[0];
std::vector<bool> inN(n);
// Stop the algo is the highest point u, which is the target tree top, is below a threshold
// Addition from original algo to limit over segmentaton
if (u->z < th_tree)
{
p.update(ni);
}
else
{
if (p.check_interrupt())
{
for (unsigned int i = 0 ; i < U.size() ; i++) delete U[i]; // # nocov
delete dummy; // # nocov
p.exit(); // # nocov
}
p.update(ni-n);