-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindBoltLocations.cpp
More file actions
2146 lines (1744 loc) · 76.6 KB
/
FindBoltLocations.cpp
File metadata and controls
2146 lines (1744 loc) · 76.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 <iostream>
#include <fstream>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <TFile.h>
#include "Configuration.hpp"
#include "featureFunctions.hpp"
#include <opencv2/features2d.hpp> //Blob
#include "PMTIdentified.hpp"
#include "bwlabel.hpp"
#include<cmath>
#include "hough_ellipse.hpp"
#include "ellipse_detection_2.1.hpp" //ellipse detection fast
#include "FeatureTTree.hpp"
#include "openblobdetector.hpp"
using std::string;
using std::vector;
using namespace cv;
void fill_ttree_blobs( const vector<OpenBlobDetector::Center>& blobinfo, ImageData & imagedata ){
unsigned entry=0;
for ( const OpenBlobDetector::Center & blob : blobinfo ){
BlobData b;
b.entry = entry++;
b.x = blob.location.x;
b.y = blob.location.y;
b.area = blob.area;
b.circularity = blob.circularity;
b.inertia = blob.inertia;
b.convexity = blob.convexity;
b.intensity = blob.intensity;
// here we need to calculate the other blob parameters!
imagedata.AddBlob( b );
}
}
void fill_image_ttree( int imgnum, ImageData& imtt, std::vector<float>b_range ){
imtt.ips.imgnum = imgnum;
imtt.ips.do_clahe = config::Get_int ( "do_clahe" );
imtt.ips.clahe_gridsize = config::Get_int ( "clahe_gridsize" );
imtt.ips.clahe_cliplimit = config::Get_int ( "clahe_cliplimit" );
imtt.ips.do_blur = config::Get_int ( "do_gaus_blur" );
imtt.ips.blur_pixels = config::Get_int ( "blurpixels" );
imtt.ips.blur_sigma = config::Get_int ( "blursigma" );
imtt.ips.do_bilat = config::Get_int ( "do_bifilter" );
imtt.ips.bilat_sigcolor = config::Get_int ( "sigColor" );
imtt.ips.bilat_sigspace = config::Get_int ( "sigSpace" );
imtt.ips.blob_min_thres = config::Get_int ( "blob_minThreshold" );
imtt.ips.blob_max_thres = config::Get_int ( "blob_maxThreshold" );
imtt.ips.blob_filter_area = config::Get_int ( "blob_filterByArea" );
imtt.ips.blob_min_area = config::Get_double( "blob_minArea" );
imtt.ips.blob_max_area = config::Get_double( "blob_maxArea" );
imtt.ips.blob_filter_circ = config::Get_int ( "blob_filterByCircularity" );
imtt.ips.blob_min_circ = config::Get_double( "blob_minCircularity" );
imtt.ips.blob_max_circ = config::Get_double( "blob_maxCircularity" );
imtt.ips.blob_filter_conv = config::Get_int ( "blob_filterByConvexity" );
imtt.ips.blob_min_conv = config::Get_double( "blob_minConvexity" );
imtt.ips.blob_max_conv = config::Get_double( "blob_maxConvexity" );
imtt.ips.blob_filter_iner = config::Get_int ( "blob_filterByInertia" );
imtt.ips.blob_min_iner = config::Get_double( "blob_minInertiaRatio" );
imtt.ips.blob_max_iner = config::Get_double( "blob_maxInertiaRatio" );
imtt.ips.ehough_minhits = config::Get_int ( "ellipse_hough_minhits" );
imtt.ips.ehough_threshold = config::Get_int ( "ellipse_hough_threshold" );
imtt.ips.ehough_drscale = config::Get_double( "ellipse_hough_drscale" );
imtt.ips.ehough_nbins_bb = unsigned((b_range[1]-b_range[0]+20)*config::Get_double ( "ellipse_hough_nbins_bb_scale" ));
imtt.ips.ehough_nbins_ee = config::Get_int ( "ellipse_hough_nbins_ee" );
imtt.ips.ehough_nbins_phiphi = config::Get_int ( "ellipse_hough_nbins_phiphi" );
imtt.ips.ehough_nbins_x = config::Get_int ( "ellipse_hough_nbins_x" );
imtt.ips.ehough_nbins_y = config::Get_int ( "ellipse_hough_nbins_y" );
imtt.ips.ehough_bbmin = b_range[0]-10;//config::Get_double( "ellipse_hough_bbmin" );
imtt.ips.ehough_bbmax = b_range[1]+10;//config::Get_double( "ellipse_hough_bbmax" );
imtt.ips.ehough_eemin = config::Get_double( "ellipse_hough_eemin" );
imtt.ips.ehough_eemax = config::Get_double( "ellipse_hough_eemax" );
imtt.ips.ehough_phimin = config::Get_double( "ellipse_hough_phimin" );
imtt.ips.ehough_phimax = config::Get_double( "ellipse_hough_phimax" );
imtt.ips.ehough_xmin = config::Get_double( "ellipse_hough_xmin" );
imtt.ips.ehough_xmax = config::Get_double( "ellipse_hough_xmax" );
imtt.ips.ehough_ymin = config::Get_double( "ellipse_hough_ymin" );
imtt.ips.ehough_ymax = config::Get_double( "ellipse_hough_ymax" );
}
// RGB to CMYK conversion
void rgb2cmyk(const cv::Mat& img, std::vector<cv::Mat>& cmyk ) {
// Allocate cmyk to store 4f componets
for (int i = 0; i < 4; i++) {
cmyk.push_back(cv::Mat(img.size(), CV_8UC1));
}
// Get rgb
std::vector<cv::Mat> rgb;
cv::split(img, rgb);
// rgb to cmyk
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
float r = (int)rgb[2].at<uchar>(i, j) / 255.;
float g = (int)rgb[1].at<uchar>(i, j) / 255.;
float b = (int)rgb[0].at<uchar>(i, j) / 255.;
float k = std::min(std::min(1- r, 1- g), 1- b);
cmyk[0].at<uchar>(i, j) = (1 - r - k) / (1 - k) * 255.;
cmyk[1].at<uchar>(i, j) = (1 - g - k) / (1 - k) * 255.;
cmyk[2].at<uchar>(i, j) = (1 - b - k) / (1 - k) * 255.;
cmyk[3].at<uchar>(i, j) = 255 - k * 255.;
}
}
}
/// return image of color by index
/// ret_rgb==true, indicies go red, green, blue
/// ret_rgb==false, indices go cyan, magenta, yellow, K
Mat output_image_by_color( const cv::Mat& image, bool ret_rgb, unsigned index, std::string infname, bool write_images=false ){
std::vector<cv::Mat> cmyk;
rgb2cmyk( image, cmyk );
std::vector<cv::Mat> rgb;
cv::split( image, rgb );
TH1D* red = new TH1D("color_red" ,"Red; intensity; pixel count",256,-0.5,255.5);
TH1D* green = new TH1D("color_green" ,"Green; intensity; pixel count",256,-0.5,255.5);
TH1D* blue = new TH1D("color_blue" ,"Blue; intensity; pixel count",256,-0.5,255.5);
TH1D* cyan = new TH1D("color_cyan" ,"Cyan; intensity; pixel count",256,-0.5,255.5);
TH1D* magenta = new TH1D("color_magenta","Magenta; intensity; pixel count",256,-0.5,255.5);
TH1D* yellow = new TH1D("color_yellow" ,"Yellow; intensity; pixel count",256,-0.5,255.5);
TH1D* K = new TH1D("color_K" ,"K; intensity; pixel count",256,-0.5,255.5);
std::vector< TH1D* > hrgb = {red, green, blue};
std::vector< TH1D* > hcmyk = {cyan, magenta, yellow, K};
for (unsigned icol=0; icol<rgb.size(); ++icol ){
const Mat& img = rgb[ icol ];
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int intensity = img.at<uchar>(i, j);
hrgb[icol]->Fill( intensity );
}
}
}
for (unsigned icol=0; icol<cmyk.size(); ++icol ){
const Mat& img = cmyk[ icol ];
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int intensity = img.at<uchar>(i, j);
hcmyk[icol]->Fill( intensity );
}
}
}
std::vector< string > crgb{"red","green","blue"};
std::vector< string > ccmyk{"cyan","magenta","yellow","K"};
if (write_images){
for ( unsigned i=0; i<rgb.size(); ++i ){
string outputname = build_output_filename (infname, crgb[i]);
imwrite ( outputname, rgb[i] );
}
for ( unsigned i=0; i<cmyk.size(); ++i ){
string outputname = build_output_filename (infname, ccmyk[i]);
imwrite ( outputname, cmyk[i] );
}
}
if (ret_rgb) return rgb[index];
return cmyk[index];
}
/// equalize each color and then get K image to return
Mat equalize_by_color( const cv::Mat& image, std::string infname, bool write_images=false ){
int gridsize = config::Get_int( "clahe_gridsize" );
int cliplimit = config::Get_int( "clahe_cliplimit" );
Ptr<CLAHE> clahe = createCLAHE();
clahe->setClipLimit( cliplimit );
clahe->setTilesGridSize( cv::Size( gridsize, gridsize ) );
std::vector<cv::Mat> rgb;
cv::split( image, rgb );
std::vector<cv::Mat> rgb_eq = rgb;
for ( unsigned i=0; i<rgb.size(); ++i ){
clahe->apply( rgb[0], rgb_eq[0] );
}
Mat rgb_rejoined;
cv::merge( &rgb_eq[0], 3, rgb_rejoined );
std::vector<cv::Mat> cmyk;
rgb2cmyk( rgb_rejoined, cmyk );
TH1D* red = new TH1D("color_redeq" ,"Red (equalized); intensity; pixel count",256,-0.5,255.5);
TH1D* green = new TH1D("color_greeneq" ,"Green (equalized); intensity; pixel count",256,-0.5,255.5);
TH1D* blue = new TH1D("color_blueeq" ,"Blue (equalized); intensity; pixel count",256,-0.5,255.5);
TH1D* cyan = new TH1D("color_cyaneq" ,"Cyan (equalized); intensity; pixel count",256,-0.5,255.5);
TH1D* magenta = new TH1D("color_magentaeq","Magenta (equalized); intensity; pixel count",256,-0.5,255.5);
TH1D* yellow = new TH1D("color_yelloweq" ,"Yellow (equalized); intensity; pixel count",256,-0.5,255.5);
TH1D* K = new TH1D("color_Keq" ,"K (equalized); intensity; pixel count",256,-0.5,255.5);
std::vector< TH1D* > hrgb = {red, green, blue};
std::vector< TH1D* > hcmyk = {cyan, magenta, yellow, K};
for (unsigned icol=0; icol<rgb.size(); ++icol ){
const Mat& img = rgb_eq[ icol ];
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int intensity = img.at<uchar>(i, j);
hrgb[icol]->Fill( intensity );
}
}
}
for (unsigned icol=0; icol<cmyk.size(); ++icol ){
const Mat& img = cmyk[ icol ];
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int intensity = img.at<uchar>(i, j);
hcmyk[icol]->Fill( intensity );
}
}
}
std::vector< string > crgb{"redeq","greeneq","blueeq"};
std::vector< string > ccmyk{"cyaneq","magentaeq","yelloweq","Keq"};
if (write_images){
{
string outputname = build_output_filename (infname, "color_equalized");
imwrite ( outputname, rgb_rejoined );
}
for ( unsigned i=0; i<rgb.size(); ++i ){
string outputname = build_output_filename (infname, crgb[i]);
imwrite ( outputname, rgb_eq[i] );
}
for ( unsigned i=0; i<cmyk.size(); ++i ){
string outputname = build_output_filename (infname, ccmyk[i]);
imwrite ( outputname, cmyk[i] );
}
}
return cmyk[3];
}
/// input is image_clahe (grayscale/bw image)
/// draw blobs on blob_circles (an empty Mat object)
/// writes image if write_images is set to false
vector< Vec3f > blob_detect( const Mat& image_clahe , Mat& blob_circles, bool write_images, const std::string& infname,
std::vector < KeyPoint >& keypoints, ImageData& imagedata ){
//Blob detection
Mat img_blob = image_clahe.clone ();
// Setup SimpleBlobDetector parameters.
OpenBlobDetector::Params params;
//detect white
//params.filterByColor=true;
params.blobColor = 255;
// Change thresholds
params.minThreshold = config::Get_int ("blob_minThreshold");
params.maxThreshold = config::Get_int ("blob_maxThreshold");
// Filter by Area.
params.filterByArea = config::Get_int ("blob_filterByArea");
params.minArea = config::Get_double ("blob_minArea");
params.maxArea = config::Get_double ("blob_maxArea");
// Filter by Circularity
params.filterByCircularity = config::Get_int ("blob_filterByCircularity");
params.minCircularity = config::Get_double ("blob_minCircularity");
//Filter by distance
params.minDistBetweenBlobs = config::Get_double ("blob_minDistBetweenBlobs");
// Filter by Convexity
params.filterByConvexity = config::Get_int ("blob_filterByConvexity");
params.minConvexity = config::Get_double ("blob_minConvexity");
// Filter by Inertia
params.filterByInertia = config::Get_int ("blob_filterByInertia");
params.minInertiaRatio = config::Get_double ("blob_minInertiaRatio");
// Set up the detector with set parameters.
Ptr < OpenBlobDetector > detector = OpenBlobDetector::create (params);
// Detect blobs.
detector->detect (img_blob, keypoints );
fill_ttree_blobs( detector->blobinfo, imagedata );
//blob vector will contain x,y,r
vector < Vec3f > blobs;
for (KeyPoint keypoint:keypoints) {
//Point center1 = keypoint.pt;
int x = keypoint.pt.x;
int y = keypoint.pt.y;
float r = ((keypoint.size) + 0.0) / 2;
Vec3f temp;
temp[0] = x;
temp[1] = y;
temp[2] = r;
blobs.push_back (temp);
}
//draw_found_center (blobs, blob_circles);
blob_circles = Mat::zeros (image_clahe.size (), image_clahe.type ());
draw_foundblobs( blobs, blob_circles );
if ( write_images ) {
//Draws circle from data to the input image
Mat img_blob_map = image_clahe.clone();
draw_circle_from_data (blobs, img_blob_map, Scalar (0, 0, 255));
string outputname = build_output_filename (infname, "blob");
imwrite (outputname, img_blob_map);
// Make image that just has circle centers from blob detection
outputname = build_output_filename (infname, "blobCandidate");
imwrite (outputname, blob_circles);
}
return blobs;
}
Mat apply_gaussian_blur( const Mat& image, bool write_image, const std::string& infname ){
Mat img_blur = image.clone ();
//bool verbose = config::Get_int("verbosity");
bool do_gaus_blur = (bool) config::Get_int ("do_gaus_blur");
if ( do_gaus_blur ) {
int blurpixels = config::Get_int ("blurpixels"); // size of kernel in pixels (must be odd)
double blursigma = config::Get_double ("blursigma"); // sigma of gaussian in pixels
GaussianBlur( image, img_blur, Size(blurpixels, blurpixels), blursigma);
if ( write_image ) {
string outputname = build_output_filename (infname, "gausblur");
imwrite (outputname, img_blur);
}
}
return img_blur;
}
Mat apply_bilateral_filter( const Mat& img_blur, bool write_image, const std::string& infname ){
bool do_bifilter = (bool) config::Get_int ("do_bifilter");
Mat img_flt = img_blur.clone ();
if ( do_bifilter ) {
int d = config::Get_int ("d"); // value 5-9 distance around each pixel to filter (must be odd)
int sigColor = config::Get_int ("sigColor"); // range of colours to call the same
int sigSpace = config::Get_int ("sigSpace"); // ???
bilateralFilter (img_blur, img_flt, d, sigColor, sigSpace);
if (write_image) {
string outputname = build_output_filename (infname, "bifilter");
imwrite (outputname, img_flt);
}
}
return img_flt;
}
Mat apply_sobel_edge( const Mat& img_flt, bool write_image, const std::string& infname ){
bool do_sobel = (bool) config::Get_int ("do_sobel");
Mat grad = img_flt.clone ();
if ( do_sobel ) {
int scale = config::Get_int ("scale");
int delta = config::Get_int ("delta");
int ddepth = CV_16S;
/// Generate grad_x and grad_y
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
//Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );
Sobel (img_flt, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs (grad_x, abs_grad_x);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel (img_flt, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs (grad_y, abs_grad_y);
/// Total Gradient (approximate)
addWeighted (abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
if ( write_image ) {
string outputname = build_output_filename (infname, "sobel");
imwrite (outputname, grad);
}
}
return grad;
}
Mat apply_canny_edge( const Mat& grad, bool write_image, const std::string& infname ){
bool do_canny = (bool) config::Get_int ("do_canny");
int thresh_low = config::Get_int ("thresh_low"); //The gradient value below thresh_low will be discarded.
int thresh_high = config::Get_int ("thresh_high"); //The gradient value above thresh_high will be used. The inbetween gradient is kept if \the edge is connected.
Mat img_can = grad.clone();
if (do_canny) {
Canny (grad, img_can, thresh_low, thresh_high);
if ( write_image ) {
string outputname = build_output_filename (infname, "canny");
imwrite (outputname, img_can);
}
}
return img_can;
}
// equalize image using clahe
Mat apply_clahe( const Mat& img_can, bool write_image, const std::string& infname ){
bool do_clahe = (bool)config::Get_int( "do_clahe" );
Mat image_clahe;
if ( do_clahe ){
std::cout<<"Applying equalization"<<std::endl;
int gridsize = config::Get_int( "clahe_gridsize" );
int cliplimit = config::Get_int( "clahe_cliplimit" );
Ptr<CLAHE> clahe = createCLAHE();
clahe->setClipLimit( cliplimit );
clahe->setTilesGridSize( cv::Size( gridsize, gridsize ) );
clahe->apply( img_can, image_clahe );
std::cout<<"Equalized"<<std::endl;
if ( write_image ) {
string outputname = build_output_filename (infname, "clahe");
imwrite (outputname, image_clahe);
}
} else {
image_clahe = img_can.clone();
}
return image_clahe;
}
void fast_ellipse_detection( const vector<Vec3f > & blobs, Mat& image_ellipse, bool write_image, const std::string& infname ){ //, const MedianTextData & mtd ){
int de_min_major = config::Get_int( "de_min_major" );//80;
int de_max_major = config::Get_int( "de_max_major" );//160;
int de_min_minor = config::Get_int( "de_min_minor" );//80;
int de_max_minor = config::Get_int( "de_max_minor" );//160;
int de_threshold = config::Get_int( "de_threshold" );//4;
std::cout<<"before ellipse"<<std::endl;
//Fast ellipse detection
std::vector<ParametricEllipse> f_ellipses= detect_ellipse(blobs,
de_min_major, de_max_major,
de_min_minor, de_max_minor, de_threshold );
//Filling PMTIdentified vector. Data is obtained from Fast ellipse detection.
std::vector< PMTIdentified > f_ellipse_pmts;
for( ParametricEllipse ellipses: f_ellipses ) {
// a = b / sqrt( 1-e^2 )
// b/a = sqrt( 1-e^2 )
// (b/a)^2 = 1 - e^2
// e^2 = 1-(b/a)^2
// e = sqrt( 1- (b/a)^2 )
float mya = ellipses.a;
float myb = ellipses.b;
float myphi = ellipses.alpha;
if ( myb > mya ){
float tmp = mya;
mya = myb;
myb = tmp;
myphi += pi/2;
}
ellipse_st pmtloc{ myb,
std::sqrt( 1 - (myb/mya)*(myb/mya) ),
myphi,
xypoint( ellipses.centre.x, ellipses.centre.y)
};
std::vector< Vec3f > boltlocs = ellipses.bolts;
std::vector< float > dists = ellipses.dist;
f_ellipse_pmts.push_back( PMTIdentified( pmtloc, boltlocs, dists, 0 ) );
}
//Angle made by bolts with vertical(12 O' clock)
TH1D * fhangboltel = new TH1D ("fhangboltel", "Angles of bolts (fast ellipse); angle (deg)", 360, 0., 360.);
//Difference in angle from expected angle of the bolt.
TH1D * fhdangboltel = new TH1D ("fhdangboltel", "Angle of bolt from expected (fast ellipse); #Delta angle (deg)", 60, -15., 15.);
for (const PMTIdentified & pmt : f_ellipse_pmts) {
for ( const float &ang : pmt.angles) {
fhangboltel->Fill (ang);
}
for ( const float &dang : pmt.dangs) {
fhdangboltel->Fill (dang);
}
}
// look for duplicate bolts and keep only best matches
prune_bolts_super_improved( f_ellipse_pmts, 4 );
// remove pmts below threshold (9 bolts)
prune_pmts_improved( f_ellipse_pmts );//, 12, "f_ellipsehough" );
//draw ellipses with line showing shortest distance from the point to the ellipse.
//draw_ellipses(f_ellipses, image_ellipse );
for ( const PMTIdentified& her : f_ellipse_pmts ){
if ( her.bolts.size() < 9 ) continue;
Size axes( int(her.circ.get_a()), int(her.circ.get_b()) );
Point center( int(her.circ.get_xy().x), int(her.circ.get_xy().y) );
ellipse( image_ellipse, center, axes, RADTODEG( her.circ.get_phi() ), 0., 360, Scalar (255, 102, 255), 2 );
Scalar my_color( 0, 0, 255 );
for ( const Vec3f& xyz : her.bolts ){
circle( image_ellipse, Point( xyz[0], xyz[1] ), 3, my_color, 1, 0 );
//image_ellipse.at<Scalar>( xy.x, xy.y ) = my_color;
}
}
// annotate with bolt numbers and angles
overlay_bolt_angle_boltid( f_ellipse_pmts, image_ellipse );
if (write_image){
string outputname = build_output_filename (infname, "fast_ellipses");
imwrite(outputname, image_ellipse);
}
//Fill ellipse_dist histogram
TH1D * f_ellipse_dist = new TH1D ("f_ellipse_dist",
"Distance from bolt to fast PMT ellipse; distance (pixels); Count/bin",
51, -0.5, 49.5);
for (const PMTIdentified & pmt : f_ellipse_pmts) {
for (const float dist : pmt.dists) {
f_ellipse_dist->Fill (dist);
}
}
//trialend
}
void pmtidentified_histograms( const std::vector< PMTIdentified > & ellipse_pmts, const std::string & tag, const float& nrows, const float& ncols ){
// histogram PMT ellipse parameters
TH1D * hpmt_locx = new TH1D( (tag+"hpmt_locx").c_str(),"PMT location ; x (pixels); counts/bin",120,0.,4000.);
TH1D * hpmt_locy = new TH1D( (tag+"hpmt_locy").c_str(),"PMT location ; y (pixels); counts/bin",90,0.,3000.);
TH1D * hpmt_a = new TH1D( (tag+"hpmt_a").c_str(),"PMT a ; a (pixels); counts/bin",100,0,300);
TH1D * hpmt_b = new TH1D( (tag+"hpmt_b").c_str(),"PMT b ; b (pixels); counts/bin",100,0,300);
TH1D * hpmt_area = new TH1D( (tag+"hpmt_area").c_str(),"PMT area ; area (px^2); counts/bin",200,0,200000);
TH1D * hpmt_phi = new TH1D( (tag+"hpmt_phi").c_str(),"PMT phi ; phi (radians); counts/bin",100, 0, 2*pi );
TH1D * hpmt_e = new TH1D( (tag+"hpmt_e").c_str(),"PMT e ; eccentricity; counts/bin",100, 0, 1.0 );
TH1D * hpmt_pkval= new TH1D( (tag+"hpmt_pkval").c_str(),"PMT peakval ; peakval; counts/bin",256, -0.5, 255.5 );
// histogram PMT phi as function of locations
TH2D * hpmt_phixy = new TH2D( (tag+"hpmt_phixy").c_str(),"PMT ellipse angle ; x (pixels); y (pixels)",100,0.,4000.,75,0.,3000.);
TH2D * hpmt_phixy0to90 = new TH2D( (tag+"hpmt_phixy0to90").c_str(),"PMT ellipse angle(0-90) ; x (pixels); y (pixels)",100,0.,4000.,75,0.,3000.);
TH2D * hpmt_axy = new TH2D( (tag+"hpmt_axy").c_str(),"PMT ellipse a ; x (pixels); y (pixels)",100,0.,4000.,75,0.,3000.);
TH2D * hpmt_bxy = new TH2D( (tag+"hpmt_bxy").c_str(),"PMT ellipse b ; x (pixels); y (pixels)",100,0.,4000.,75,0.,3000.);
TH2D * hpmt_areaxy = new TH2D( (tag+"hpmt_areaxy").c_str(),"PMT ellipse area ; x (px^2); y (pixels)",100,0.,4000.,75,0.,3000.);
TH2D * hpmt_exy = new TH2D( (tag+"hpmt_exy").c_str(),"PMT ellipse e ; x (pixels); y (pixels)",100,0.,4000.,75,0.,3000.);
TH2D * hpmt_houghpk = new TH2D( (tag+"hpmt_houghpk").c_str(),"PMT hough peak ; x (pixels); y (pixels)",100,0.,4000.,75,0.,3000.);
// histogram of area as function of radius from center of image
TH2D * havsr = new TH2D( (tag+"hpmt_avsr").c_str(),"PMT area vs distance from center of image; r (pixels); area (px^2)", 200, 0., 4000., 200, 0., 1000000. );
for ( const PMTIdentified& her : ellipse_pmts ){
float x = her.circ.get_xy().x ;
float y = nrows - her.circ.get_xy().y ; // axis start from left bottom corner y^->x
float aa = her.circ.get_a();
float bb = her.circ.get_b();
float ee = her.circ.get_e();
float area = aa*bb*pi;
float phi = her.circ.get_phi();
hpmt_pkval->Fill( her.peakval );
hpmt_houghpk->Fill( x, y, her.peakval );
hpmt_locx->Fill( x );
hpmt_locy->Fill( y );
hpmt_a->Fill( aa );
hpmt_b->Fill( bb );
hpmt_area->Fill( area );
hpmt_phi->Fill( phi );
hpmt_e->Fill( ee );
hpmt_phixy->Fill( x, y, phi );
float theta = (phi>90)?180.0-phi:phi;
hpmt_phixy0to90->Fill(x,y,theta);
hpmt_axy->Fill( x, y, aa );
hpmt_bxy->Fill( x, y, bb );
hpmt_areaxy->Fill( x, y, area );
hpmt_exy->Fill( x, y, ee );
// distance from center of image?
float r = std::sqrt( (x-ncols/2.0)*(x-ncols/2.0) + (y-nrows/2.0)*(y-nrows/2.0) );
havsr->Fill( r, area );
}
}
void histogram_blobs( const vector< Vec3f >& blobs, const std::string & tag ){
std::ostringstream hname;
hname << tag << "_blob_size";
TH1D* hblobsize = new TH1D( hname.str().c_str(), " ; Blob size; counts/bin", 500, 0.5, 500.5 );
hname <<tag<< "_xy";
TH2D* hblobsizexy = new TH2D( hname.str().c_str(), "Blob size; X; Y", 1000, 0., 4000., 750,0.,3000.);
for( const Vec3f& b: blobs){
float x = b[0];
float y = 3000 - b[1];
float sz = b[2] * b[2] * pi;
hblobsize->Fill( sz );
hblobsizexy->Fill( x, y, sz );
}
TH1D* blobsize = new TH1D((tag+"_Blob_radii").c_str(), "Size of Blob; Size; counts/bin", 500, -0.5, 49.5 );
TH1D* blobsdistance1 = new TH1D((tag+"_First_Blob_Dist").c_str(), "Min distance with closest(first) blob; dist; counts/bin",5000. , -0.5, 4999.5 );
TH1D* blobsdistance2 = new TH1D((tag+"_Second_Blob_Dist").c_str(), "Min distance with second closest blobs; dist; counts/bin",5000. , -0.5, 4999.5 );
TH1D* blobsdistance3 = new TH1D((tag+"_Third_Blob_Dist").c_str(), "Min distance with third closest blobs; dist; counts/bin",5000. , -0.5, 4999.5 );
TH1D* blobsdensity = new TH1D((tag+"Blobs_density").c_str(), "Blobs Density; Density(num/35^2Pi); counts/bin",50. , -0.5, 49.5 );
TH2D* blobsdensity2D = new TH2D((tag+"Blobs_density_2D").c_str(), "Blobs Density_2D;X;Y",1000, 0., 4000., 750,0.,3000. );
//fill the blob density histogra
//std::vector<int> ind;
for(unsigned i=0;i<blobs.size();i++){
Vec3f blb = blobs[i];
int count =1;
for(unsigned j=0; j<blobs.size(); j++){
if(j==i)continue;
double dist = sqrt((blobs[j][0]-blb[0])*(blobs[j][0]-blb[0])+(blobs[j][1]-blb[1])*(blobs[j][1]-blb[1]));
if(dist<35){count++;}
}
blobsdensity->Fill(count);
blobsdensity2D->Fill(blb[0],2750.-blb[1],count);
}
//end
int first_ind=-1; //for recording index of first min distance blob
int sec_ind =-1;
for(int i=0;i<int(blobs.size());i++){
Vec3f blb = blobs[i];
blobsize->Fill(blb[2]);
double mindist = 10000000;
double mindist2 = 10000000;
double mindist3 = 10000000;
for(int j=0; j<int(blobs.size()); j++){
if(j==i)continue;
double dist = sqrt((blobs[j][0]-blb[0])*(blobs[j][0]-blb[0])+(blobs[j][1]-blb[1])*(blobs[j][1]-blb[1]));
if(dist<mindist){mindist = dist; first_ind=j;}
}
for(int j=0; j<int(blobs.size()); j++){
if(j==i || j==first_ind)continue;
double dist2 = sqrt((blobs[j][0]-blb[0])*(blobs[j][0]-blb[0])+(blobs[j][1]-blb[1])*(blobs[j][1]-blb[1]));
if(dist2<mindist2){mindist2 = dist2; sec_ind = j; }
}
for(int j=0; j<int(blobs.size()); j++){
if(j==i || j==first_ind || j==sec_ind)continue;
double dist3 = sqrt((blobs[j][0]-blb[0])*(blobs[j][0]-blb[0])+(blobs[j][1]-blb[1])*(blobs[j][1]-blb[1]));
if(dist3<mindist3){mindist3 = dist3; }
}
if(mindist!=10000000){ blobsdistance1->Fill(mindist);}
if(mindist2!=10000000){ blobsdistance2->Fill(mindist2);}
if(mindist3!=10000000){ blobsdistance3->Fill(mindist3);}
}
}
void histogram_stddev(const std::vector< PMTIdentified >ellipse_pmts, std::string tag){
TH2D* blobsdensity2D = new TH2D((tag+"stddev with 15").c_str(), "Std Deviation;X;Y",1000, 0., 4000., 750,0.,3000. );
TH2D* blobsdensity2D1 = new TH2D((tag+"stddev with mean").c_str(), "Std Deviation;X;Y",1000, 0., 4000., 750,0.,3000. );
TH2D* blobsdensity2D2 = new TH2D((tag+"stddev with median").c_str(), "Std Deviation;X;Y",1000, 0., 4000., 750,0.,3000. );
for(PMTIdentified her: ellipse_pmts){
float a = her.circ.get_xy().x ;
float b = her.circ.get_xy().y ; // axis start from left bottom corner y^->x
//float aa = her.circ.get_a();
//float bb = her.circ.get_b();
//float ee = her.circ.get_e();
//float area = aa*bb*pi;
//float phi = her.circ.get_phi();
vector<float>data;
for(unsigned j=0; j<her.bolts.size(); j++){
float x0=her.bolts[j][0]-a;
float y0=her.bolts[j][1]-b;
float min_ang=362;
for(unsigned k=0; k<her.bolts.size(); k++){
if(j==k){continue;}
float x1=her.bolts[k][0]-a;
float y1=her.bolts[k][1]-b;
float theta = std::acos(fabs(((x0*x1)+(y0*y1))/(std::sqrt(((x0*x0)+(y0*y0))*((x1*x1)+(y1*y1))))));
theta = theta*180.0/acos(-1);
if(theta<min_ang){
min_ang=theta;
}
}
data.push_back(min_ang);
}
//based on mode
//have to sort first
std::vector<float>dmedian=data;
for(unsigned i=0; i<data.size();i++){
float d=dmedian[i];
int ind=-1;
for(unsigned k=i+1;k<data.size();k++){
if(dmedian[k]<d){d=dmedian[k]; ind=k;}
}
if(ind>=0){ dmedian[ind]=data[i]; dmedian[i]=d;}
}
float median = dmedian[data.size()/2];
float avg=15.;//0;
float mean=0.0;
for(float x:data){
mean +=x;
}
mean /= data.size();
//calculating stddev
float sum=0;
for(float x:data){
sum += (x-avg)*(x-avg);
}
//for mean
float sum1=0;
for(float x:data){
sum1 += (x-mean)*(x-mean);
}
//median
float sum2=0;
for(float x:data){
sum2 += (x-median)*(x-median);
}
float stddev = sqrt(sum/data.size());
float stddev1 = sqrt(sum1/data.size());
float stddev2 = sqrt(sum2/data.size());
blobsdensity2D->Fill(a,2750.-b,stddev);
blobsdensity2D1->Fill(a,2750.-b,stddev1);
blobsdensity2D2->Fill(a,2750.-b,stddev2);
}
}
void ellipses_to_ttree( const std::vector< PMTIdentified >& ellipse_pmts, ImageData& imagedata ){
for ( const PMTIdentified& pmt : ellipse_pmts ){
EllipseData ed( pmt.pmtid, pmt.circ[0], pmt.circ[1],
pmt.circ.get_a(), pmt.circ.get_b(), pmt.circ.get_e(), pmt.circ.get_phi(),
pmt.bolts.size() );
for ( const Vec3f bolt : pmt.bolts ){
// find closest matching blob
unsigned idxmatch=0;
float distmin2 =1000000;
for ( unsigned idx=0; idx<imagedata.fBlobs.size(); ++idx){
const BlobData & b = imagedata.fBlobs[idx];
float dist2 = (b.x-bolt[0])*(b.x-bolt[0]) + (b.y-bolt[1])*(b.y-bolt[1]);
if ( dist2 < distmin2 ){
idxmatch = idx;
distmin2 = dist2;
}
}
ed.blobentry.push_back( imagedata.fBlobs[idxmatch] );
}
ed.ndof = pmt.dists.size();
ed.chi2 = 0.0;
for ( float d : pmt.dists ){
ed.chi2 += d*d;
}
ed.peakval = pmt.peakval;
imagedata.AddEllipse( ed );
}
}
void pmts_to_ttree( const std::vector< PMTIdentified >& ellipse_pmts, ImageData& imagedata ){
for ( const PMTIdentified& pmt : ellipse_pmts ){
EllipseData ed( pmt.pmtid, pmt.circ[0], pmt.circ[1],
pmt.circ.get_a(), pmt.circ.get_b(), pmt.circ.get_e(), pmt.circ.get_phi(),
pmt.bolts.size() );
for ( const Vec3f bolt : pmt.bolts ){
// find closest matching blob
unsigned idxmatch=0;
float distmin2 =1000000;
for ( unsigned idx=0; idx<imagedata.fBlobs.size(); ++idx){
const BlobData & b = imagedata.fBlobs[idx];
float dist2 = (b.x-bolt[0])*(b.x-bolt[0]) + (b.y-bolt[1])*(b.y-bolt[1]);
if ( dist2 < distmin2 ){
idxmatch = idx;
distmin2 = dist2;
}
}
ed.blobentry.push_back( imagedata.fBlobs[idxmatch] );
}
ed.ndof = pmt.dists.size();
ed.chi2 = 0.0;
for ( float d : pmt.dists ){
ed.chi2 += d*d;
}
ed.peakval = pmt.peakval;
imagedata.AddPMT( ed );
}
}
void slow_ellipse_detection( const std::vector< cv::Vec3f > blobs, Mat& image_houghellipse,
bool write_image, const std::string& infname, const MedianTextData & mtd , ImageData& imagedata, std::vector<float> b_range){
bool do_ellipse_hough = (bool)config::Get_int( "do_ellipse_hough" );
if ( do_ellipse_hough ){
float bbmin = b_range[0]-10;//(float)config::Get_double("ellipse_hough_bbmin");
float bbmax = b_range[1]+10;//(float)config::Get_double("ellipse_hough_bbmax");
unsigned nbins_bb = (unsigned)((bbmax-bbmin)*config::Get_double("ellipse_hough_nbins_bb_scale"));
unsigned nbins_ee = (unsigned)config::Get_int("ellipse_hough_nbins_ee");
unsigned nbins_phiphi = (unsigned)config::Get_int("ellipse_hough_nbins_phiphi");
unsigned nbins_x = (unsigned)config::Get_int("ellipse_hough_nbins_x");
unsigned nbins_y = (unsigned)config::Get_int("ellipse_hough_nbins_y");
//# above number of bins multiply as short (2 bytes per bin)
//# therefore eg. 2 x 40 x 10 x 10 x 2300 x 1300 = 23.8 GB !!!
float eemin = (float)config::Get_double("ellipse_hough_eemin");
float eemax = (float)config::Get_double("ellipse_hough_eemax");
float phiphimin = (float)config::Get_double("ellipse_hough_phimin");
float phiphimax = (float)config::Get_double("ellipse_hough_phimax");
float xmin = (float)config::Get_double("ellipse_hough_xmin");
float xmax = (float)config::Get_double("ellipse_hough_xmax");
float ymin = (float)config::Get_double("ellipse_hough_ymin");
float ymax = (float)config::Get_double("ellipse_hough_ymax");
///===========================================================
/// Begin ellipse hough transfrom stuff
EllipseHough h ( nbins_bb, bbmin, bbmax,
nbins_ee, eemin, eemax,
nbins_phiphi, phiphimin, phiphimax,
nbins_x, xmin, xmax,
nbins_y, ymin, ymax );
h.set_minhits( config::Get_int("ellipse_hough_minhits") );
h.set_threshold( config::Get_int("ellipse_hough_threshold") );
h.set_minhits( config::Get_double("ellipse_hough_drscale") );
std::vector< xypoint > data;
for ( unsigned i=0 ; i < blobs.size(); ++i ){
//float radius = blobs[i][2];
int blobx = blobs[i][0];
int bloby = blobs[i][1];
data.push_back( xypoint( blobx , bloby ) );
}
HoughEllipseResults hers = h.find_ellipses( data );
/// take hough resutls and fill vector of PMTIdentified info
std::vector< PMTIdentified > ellipse_pmts;
for ( const HoughEllipseResult& her : hers ){
ellipse_st pmtloc{ her.e };
std::vector< Vec3f > boltlocs;
std::vector< float > dists;
for ( const xypoint& xy : her.data ){
boltlocs.push_back( Vec3f( xy.x, xy.y, 3 ) );
dists.push_back( her.e.dmin( xy ) );
}
ellipse_pmts.push_back( PMTIdentified( pmtloc, boltlocs, dists, her.peakval ) );
}
ellipses_to_ttree( ellipse_pmts, imagedata );
//Trial here.
histogram_stddev(ellipse_pmts, "before");
/// collect blobs that were put onto PMTs
std::vector< Vec3f > blobs_on_pmts;
for ( const HoughEllipseResult& her : hers ){
for ( const xypoint& xy : her.data ){
for ( const Vec3f& b : blobs ){
if ( fabs( b[0]-xy.x )< 1.0 && fabs( b[1]-xy.y ) < 1.0 ){
blobs_on_pmts.push_back( b );
break;
}
}
}
}
histogram_blobs( blobs_on_pmts, "_preprune" );
TH1D * hangboltel = new TH1D ("hangboltel", "Angles of bolts (hough ellipse); angle (deg)", 360, 0., 360.);
TH1D * hdangboltel = new TH1D ("hdangboltel", "Angle of bolt from expected (hough ellipse); #Delta angle (deg)", 60, -15., 15.);
for (const PMTIdentified & pmt : ellipse_pmts) {
for ( const float &ang : pmt.angles) {
hangboltel->Fill (ang);
}
for ( const float &dang : pmt.dangs) {
hdangboltel->Fill (dang);
}
}
std::cout<<"========================== Before Pruning PMTS ===================================="<<std::endl;
for (const PMTIdentified & pmt : ellipse_pmts) {
print_pmt_ellipse( std::cout, pmt );
//std::cout<<pmt<<std::endl;
}
if ( write_image ){
Mat image_before = image_houghellipse.clone();
for ( const PMTIdentified& her : ellipse_pmts ){
//if ( her.bolts.size() < 9 ) continue;
Size axes( int(her.circ.get_a()), int(her.circ.get_b()) );
Point center( int(her.circ.get_xy().x), int(her.circ.get_xy().y) );
ellipse( image_before, center, axes, RADTODEG( her.circ.get_phi() ), 0., 360, Scalar (255, 102, 255), 2 );
Scalar my_color( 0, 0, 255 );
for ( const Vec3f& xyz : her.bolts ){
circle( image_before, Point( xyz[0], xyz[1] ), 3, my_color, 1, 0 );
//image_ellipse.at<Scalar>( xy.x, xy.y ) = my_color;
}
}
// annotate with bolt numbers and angles
overlay_bolt_angle_boltid( ellipse_pmts, image_before );
string outputname = build_output_filename ( infname , "houghellipse_before");
std::cout<<"Writing image "<<outputname<<std::endl;
imwrite (outputname, image_before );
}
// histogram PMT locations before pruning
pmtidentified_histograms( ellipse_pmts, "preprune",image_houghellipse.rows, image_houghellipse.cols );
// prune_bolts_improved2( ellipse_pmts, hdangboltel->GetMean() );
prune_bolts_super_improved( ellipse_pmts, 4. );
//prune_bolts( ellipse_pmts, hdangboltel->GetMean() );
// look for duplicate bolts and keep only best matches
//prune_bolts( ellipse_pmts, hdangboltel->GetMean() );
// remove pmts below threshold (9 bolts)
// prune_pmts( ellipse_pmts, 9, "ellipsehough" );
//prune_pmts( ellipse_pmts, 9, "ellipsehough" );
prune_pmts_improved( ellipse_pmts );//, 10, "ellipsehough" );
std::cout<<"========================== AFTER Pruning PMTS ===================================="<<std::endl;
for (const PMTIdentified & pmt : ellipse_pmts) {
print_pmt_ellipse( std::cout, pmt );
//std::cout<<pmt<<std::endl;
}
//making histogram of angle of ellipse wrt y-axis and size
//TH2D *ellipse_feature = new TH2D("Ellipse feature", "Ellipse feature; y-value;phi(degree);size; count);
histogram_stddev(ellipse_pmts, "after_pruning");
//histogram_deviation(ellipse_pmts, "after");
//Fill ellipse_dist histogram
TH1D * ellipse_dist = new TH1D ("ellipse_dist",