-
Notifications
You must be signed in to change notification settings - Fork 0
/
frame_extraction.cpp
2818 lines (2616 loc) · 80.6 KB
/
frame_extraction.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
/*
* CPP_Birdtracker/frame_extraction.cpp - LunAero video bird tracking software
* Copyright (C) <2020> <Wesley T. Honeycutt>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
*
* This is a more efficient frame data extraction program for the LunAero birdtracker project
*
*
*/
#include "frame_extraction.hpp"
/**
* This function performs a shifting crop of the input image based on the values shiftx and shifty.
* The output image will always have BOXOUT dimensions determined from the size of the original
* image's shortest side.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param shiftx number of pixels the cropped image should be shifted in the horizontal direction
* @param shifty number of pixels the cropped image should be shifted in the vertical direction
* @return in_frame The modified in_frame from the input params
*/
static Mat shift_frame(Mat in_frame, int shiftx, int shifty) {
Mat zero_mask = Mat::zeros(in_frame.size(), in_frame.type());
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "SHIFT_X: " << shiftx << std::endl << "SHIFT_Y: " << shifty << std::endl;
LOGGING.close();
}
if ((shiftx < 0) && (shifty < 0)) { // move right and down
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "shifting case 1 - move right and down" << std::endl;
LOGGING.close();
}
in_frame(Rect(0, 0, BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty)))
.copyTo(zero_mask(Rect(abs(shiftx), abs(shifty), BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty))));
} else if (shiftx < 0) { // move right and maybe up
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "shifting case 2 - move right and maybe up" << std::endl;
LOGGING.close();
}
in_frame(Rect(0, abs(shifty), BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty)))
.copyTo(zero_mask(Rect(abs(shiftx), 0, BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty))));
} else if (shifty < 0) { // move down and maybe left
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "shifting case 3 - move down and maybe left" << std::endl;
LOGGING.close();
}
in_frame(Rect(abs(shiftx), 0, BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty)))
.copyTo(zero_mask(Rect(0, abs(shifty), BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty))));
} else { // positive moves up and left
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "shifting case 4 - move up and left" << std::endl;
LOGGING.close();
}
in_frame(Rect(abs(shiftx), abs(shifty), BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty)))
.copyTo(zero_mask(Rect(0, 0, BOXSIZE-abs(shiftx), BOXSIZE-abs(shifty))));
}
in_frame = zero_mask;
return in_frame;
}
/**
* If the moon cannot be centered properly using moment methods, this function is called. Here, the
* corner of the bounding box around the moon in the input frame is matched to the corners detected
* in the first frame. If the first frame of the video was centered properly, this will produce an
* output frame which deviates less from the intended centering function. This helps to reduce noise
* in when the contours are detected across all tiers. Corner matching is determined by comparison
* against the maximum allowable edge length declared by EDGETHRESH from settings.cfg. If this
* threshold is violated, corner matching will occur. Otherwise, traditional centering will occur.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param contour OpenCV contour, a vector of int int points
* @param plusx horizontal deviation of contour in pixels
* @param plusy vertical deviation of contour in pixels
* @return in_frame The modified in_frame from the input params
*/
static Mat corner_matching(Mat in_frame, vector<Point> contour, int plusx, int plusy) {
int shiftx = 0;
int shifty = 0;
// Point local_tl = boundingRect(contour).tl();
// Point local_br = boundingRect(contour).br();
//
// if (DEBUG_COUT) {
// LOGGING.open(LOGOUT, std::ios_base::app);
// LOGGING
// << "PLUSX: " << plusx << " PLUSY: " << plusy << std::endl
// << "LOCAL_TL = (" << local_tl.x << ", " << local_tl.y << ")" << std::endl
// << "LOCAL_BR = (" << local_br.x << ", " << local_br.y << ")" << std::endl
// << "ORIG_TL = (" << ORIG_TL.x << ", " << ORIG_TL.y << ")" << std::endl
// << "ORIG_BR = (" << ORIG_BR.x << ", " << ORIG_BR.y << ")" << std::endl;
// LOGGING.close();
// }
//
// if ((abs(plusx) > EDGETHRESH) && (abs(plusx) > EDGETHRESH)) {
// if (plusx > 0) {
// if (plusy > 0) {
// // +x, +y (touching right and bottom edges)
// shiftx = (local_tl.x - ORIG_TL.x);
// shifty = (local_tl.y - ORIG_TL.y);
// } else {
// // +x, -y (touching right and top edges)
// shiftx = (local_tl.x - ORIG_TL.x);
// shifty = (local_br.y - ORIG_BR.y);
// }
// } else {
// if (plusy > 0) {
// // -x, +y (touching left and bottom edges)
// shiftx = (local_br.x - ORIG_BR.x);
// shifty = (local_tl.y - ORIG_TL.y);
// } else {
// // -x, -y (touching left and top edges)
// shiftx = (local_br.x - ORIG_BR.x);
// shifty = (local_br.y - ORIG_BR.y);
// }
// }
// } else if (abs(plusx) > EDGETHRESH) {
// if (plusx > 0) {
// // +x (touching right edge)
// shiftx = (local_tl.x - ORIG_TL.x);
//
// } else {
// // -x (touching left edge)
// shiftx = (local_br.x - ORIG_BR.x);
//
// }
// } else if (abs(plusy) > EDGETHRESH) {
// if (plusy > 0) {
// // +y (touching bottom edge)
// shifty = (local_tl.y - ORIG_TL.y);
//
// } else {
// // -y (touching top edge)
// shifty = (local_br.y - ORIG_BR.y);
//
// }
// }
in_frame = shift_frame(in_frame, shiftx/2, shifty/2);
return in_frame;
}
/**
* This function tests the moon contour to determine the degree of shift required to center it in a
* frame.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param contour OpenCV contour, a vector of int int points
* @return outplus integer vector of horizontal and vertical deviation of the primary contour
*/
static vector <int> test_edges(Mat in_frame, vector<Point> contour, int te_ret) {
int plusx = 0;
int plusy = 0;
// Fetch the boundary of this primary contour
Rect rect = boundingRect(contour);
/*
* Cases:
* -1 : error
* 0 : no edge touching
* 1 : touching left edge only
* 2 : touching right edge only
* 3 : touching top and left edge
* 4 : touching bottom and left edge
* 5 : touching top and right edge
* 6 : touching bottom and right edge
* 7 : touching top only
* 8 : touching bottom only
*/
if ((te_ret == 1) || (te_ret == 3) || (te_ret == 7)) {
//touching left edge only
plusx = rect.br().x - ORIG_BR.x;
plusy = rect.br().y - ORIG_BR.y;
} else if ((te_ret == 2) || (te_ret == 6) || (te_ret == 8)) {
//touching right edge only
plusx = rect.tl().x - ORIG_TL.x;
plusy = rect.tl().y - ORIG_TL.y;
} else if (te_ret == 4) {
//touching bottom and left edge
plusx = -(ORIG_TL.x + (ORIG_HORZ - rect.width));
plusy = (BOXSIZE - ORIG_BR.y) + (ORIG_VERT - rect.height);
} else if (te_ret == 5) {
//touching top and right edge
plusx = (BOXSIZE - ORIG_TL.x) - rect.width;
plusy = -(ORIG_BR.y - rect.height);
}
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << plusx << ", " << plusy << std::endl;
LOGGING.close();
}
vector <int> outplus;
outplus.push_back(plusx);
outplus.push_back(plusy);
return outplus;
}
/**
* This function stores the BOXSIZE variable globally. BOXSIZE is the shortest side of the input
* image dimensions.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @return status
*/
static int min_square_dim(Mat in_frame) {
BOXSIZE = min(in_frame.rows, in_frame.cols);
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "Cutting frame to size: (" << BOXSIZE << ", " << BOXSIZE << ")" << std::endl;
LOGGING.close();
}
return 0;
}
/**
* This function determines the length of the extreme top and bottom edges of the moon contour.
*
* @param contour OpenCV contour, a vector of int int points
* @return local_vec integer vector of the top and bottom edge length of the moon
*/
static vector <int> edge_width(vector<Point> contour) {
vector <int> local_vec;
Rect box = boundingRect(contour);
int top = box.tl().y;
int bot = box.br().y;
int topout = 0;
int botout = 0;
for (size_t i = 0; i<contour.size(); i++) {
if (contour[i].y == top) {
topout += 1;
}
if (contour[i].y == bot) {
botout += 1;
}
}
local_vec.push_back(topout);
local_vec.push_back(botout);
return local_vec;
}
/**
* This function determines the length of the extreme left and right edges of the moon contour.
*
* @param contour OpenCV contour, a vector of int int points
* @return local_vec integer vector of the left and right edge length of the moon
*/
static vector <int> edge_height(vector<Point> contour) {
vector <int> local_vec;
Rect box = boundingRect(contour);
int lef = box.tl().x;
int rig = box.br().x;
int lefout = 0;
int rigout = 0;
for (size_t i = 0; i<contour.size(); i++) {
if (contour[i].y == lef) {
lefout += 1;
}
if (contour[i].y == rig) {
rigout += 1;
}
}
local_vec.push_back(lefout);
local_vec.push_back(rigout);
return local_vec;
}
/**
* Performs an initial rough crop on the frame. This constructs a cropped frame which contains the
* largest contour, but does not necessarily center the contour within the frame. That is handled
* by halo_noise_and_center by determing whether the centering should use the corner_matching regime
* or simple centroid to centroid shifting. Stores the cropped in_frame to IC_FRAME global.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param framecnt int of nth frame retrieved by program
* @return status
*/
static int initial_crop(Mat in_frame, int framecnt) {
int oldvalue;
// Find largest contour
if (box_finder(in_frame, true)) {
return 1;
}
Rect box = BF_BOX;
// Create rect representing the image
Rect image_rect = Rect({}, in_frame.size());
// Edit box corners such that we have a BOXSIZE square
Point roi_tl = Point(box.tl().x - ((BOXSIZE - box.width)/2),
(box.tl().y- (BOXSIZE - box.height)/2));
Point roi_br = Point(((BOXSIZE - box.width)/2) + box.br().x,
((BOXSIZE - box.height)/2) + box.br().y);
// Correct for non BOXSIZE rounding errors, only expand BR since we check for invalid later
if (roi_br.x - roi_tl.x > BOXSIZE) {
oldvalue = (roi_br.x - roi_tl.x) - BOXSIZE;
roi_br = Point(roi_br.x - oldvalue, roi_br.y);
} else if (roi_br.x - roi_tl.x < BOXSIZE) {
oldvalue = BOXSIZE - (roi_br.x - roi_tl.x);
roi_br = Point(roi_br.x + oldvalue, roi_br.y);
}
if (roi_br.y - roi_tl.y > BOXSIZE) {
oldvalue = (roi_br.y - roi_tl.y) - BOXSIZE;
roi_br = Point(roi_br.x, roi_br.y - oldvalue);
} else if (roi_br.y - roi_tl.y < BOXSIZE) {
oldvalue = BOXSIZE - (roi_br.y - roi_tl.y);
roi_br = Point(roi_br.x, roi_br.y + oldvalue);
}
// Correct for invalid values in the new box
if (roi_tl.x < 0) {
oldvalue = -(roi_tl.x);
roi_tl = Point(0, roi_tl.y);
roi_br = Point(roi_br.x - oldvalue, roi_br.y);
}
if (roi_tl.y < 0) {
oldvalue = -(roi_tl.y);
roi_tl = Point(roi_tl.x, 0);
roi_br = Point(roi_br.x, roi_br.y - oldvalue);
}
if (roi_br.x > in_frame.cols) {
oldvalue = roi_br.x - in_frame.cols;
roi_tl = Point(roi_tl.x - oldvalue, roi_tl.y);
roi_br = Point(roi_br.x - oldvalue, roi_br.y);
}
if (roi_br.y > in_frame.rows) {
oldvalue = roi_br.y - in_frame.rows;
roi_tl = Point(roi_tl.x, roi_tl.y - oldvalue);
roi_br = Point(roi_br.x, roi_br.y - oldvalue);
}
// Make this our region of interest.
Rect roi = Rect(roi_tl, roi_br);
// Find intersection, i.e. valid crop region
Rect intersection = image_rect & roi;
// Adjust the intersection to have the correct BOXSIZE
intersection = Rect(Point(intersection.x, intersection.y), Size(BOXSIZE, BOXSIZE));
// Move intersection to the result coordinate space
Rect inter_roi = intersection - roi.tl();
// Crop the image to the intersection
Mat precrop = in_frame(intersection);
// If we have positive coordinates, then blackout the region. If not, just pass the precrop along
if ((inter_roi.x > 0) || (inter_roi.y > 0)) {
// Create black image and copy intersection
Mat zero_mask = Mat::zeros(Size(BOXSIZE, BOXSIZE), in_frame.type());
// Assign a rectangular region in precrop...
precrop(Rect(Point(0, 0),
Size(BOXSIZE-inter_roi.x, BOXSIZE-inter_roi.y)
))
// ...and copy the black masked moon there.
.copyTo(zero_mask(
Rect(
Point(inter_roi.x, inter_roi.y),
Size(BOXSIZE-inter_roi.x, BOXSIZE-inter_roi.y)
)
));
in_frame = zero_mask;
} else {
// If negative values exist, whatever, just pass it along and call it a day.
in_frame = precrop;
}
IC_FRAME = in_frame;
return 0;
}
/**
* This function tests the input contour boundaries against the boundaries of the frame. It returns a
* integer value representing the edge(s) which is/are touched by the contour. If no edges are touched,
* this function returns zero. A negative return value indicates error. Here is a table of potential
* return values:
* - -1 : error status
* - 0 : no edge touching
* - 1 : touching left edge only
* - 2 : touching right edge only
* - 3 : touching top and left edge
* - 4 : touching bottom and left edge
* - 5 : touching top and right edge
* - 6 : touching bottom and right edge
*
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param contour OpenCV contour, a vector of int int points
* @return touching_status an integer value representing if and which edge of the frame is touched
* by the contour. Returns negative status values if something went wrong.
*/
static int touching_edges(Mat in_frame, vector<Point> contour) {
// fetch the boundary rectangle for our large contour
Rect box = boundingRect(contour);
if (box.tl().x == 0) {
if (box.tl().y == 0) {
return 3;
} else if (box.br().y == in_frame.rows) {
return 4;
} else {
return 1;
}
} else if (box.br().x == in_frame.cols) {
if (box.tl().y == 0) {
return 5;
} else if (box.br().y == in_frame.rows) {
return 6;
} else {
return 2;
}
} else {
if (box.tl().y == 0) {
return 7;
} else if (box.br().y == in_frame.rows) {
return 8;
} else {
return 0;
}
}
// This should never be reached
return -1;
}
static Mat traditional_centering(Mat in_frame, vector <vector<Point>> contours, int largest, Rect box) {
// Generate masks
Mat mask(Size(in_frame.rows, in_frame.cols), in_frame.type(), Scalar(0));
Mat zero_mask(Size(BOXSIZE, BOXSIZE), in_frame.type(), Scalar(0));
// Create a mat with just the moon
Mat item(in_frame(box));
// Apply contour to mask
drawContours(mask, contours, largest, 255, FILLED);
// Transfer item to mask
item.copyTo(item, mask(box));
// Calculate the center
Point center(BOXSIZE/2, BOXSIZE/2);
Rect center_box(center.x - box.width/2, center.y - box.height/2, box.width, box.height);
// Copy the item mask to the centered box on our zero mask
item.copyTo(zero_mask(center_box));
// done
in_frame = zero_mask;
return in_frame;
}
/**
* This function is a special case of the frame preparation steps. It outputs many of the initial
* values which are used later (globals that start with the ORIG_ template) and omits some of the
* masking steps not possible on the first frame.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param framecnt int of nth frame retrieved by program
* @return in_frame The modified in_frame from the input params
*/
static int first_frame(Mat in_frame, int framecnt) {
Mat temp_frame;
// Determine the minimum dimensions of the input video
min_square_dim(in_frame);
// Do a first pass/rough crop
initial_crop(in_frame.clone(), framecnt);
in_frame = IC_FRAME;
// Make sure the black of night stays black so we can get the edge of the moon
threshold(in_frame.clone(), temp_frame, BLACKOUT_THRESH, 255, THRESH_TOZERO);
// Get contours
vector <vector<Point>> contours = contours_only(temp_frame);
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING
<< "Number of detected contours in ellipse frame: "
<< contours.size()
<< std::endl;
LOGGING.close();
}
// Find which contour is the largest
int largest_contour_index = largest_contour(contours);
drawContours(in_frame, contours, largest_contour_index, 255, 2, LINE_8);
// Store original area and perimeter of first frame
Rect box = boundingRect(contours[largest_contour_index]);
ORIG_AREA = box.area();
ORIG_PERI = arcLength(contours[largest_contour_index], true);
ORIG_VERT = box.height;
ORIG_HORZ = box.width;
// ORIG_TL = box.tl();
// ORIG_BR = box.br();
ORIG_TL = Point((BOXSIZE - box.width)/2, (BOXSIZE - box.height)/2);
ORIG_BR = Point(BOXSIZE - ((BOXSIZE - box.width)/2), BOXSIZE - ((BOXSIZE - box.height)/2));
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING
<< "box width: " << box.width << std::endl
<< "box height: " << box.height << std::endl
<< "box x: " << box.x << std::endl
<< "box y: " << box.y << std::endl
<< "box area: " << box.area() << std::endl;
LOGGING.close();
}
// // Create rect representing the image
// Rect image_rect = Rect({}, in_frame.size());
// Point roi_tl = Point(box.tl().x - ((BOXSIZE - box.width)/2), (box.tl().y- (BOXSIZE - box.height)/2));
// Point roi_br = Point(((BOXSIZE - box.width)/2) + box.br().x, ((BOXSIZE - box.height)/2) + box.br().y);
// Rect roi = Rect(roi_tl, roi_br);
//
// // Find intersection, i.e. valid crop region
// Rect intersection = image_rect & roi;
//
// // Move intersection to the result coordinate space
// Rect inter_roi = intersection - roi.tl();
//
// // Create black image and copy intersection
// Mat crop = Mat::zeros(roi.size(), in_frame.type());
// in_frame(intersection).copyTo(crop(inter_roi));
//
// in_frame = crop;
// in_frame = traditional_centering(in_frame.clone(), contours, largest_contour_index, box);
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING
<< "ORIG_AREA = "
<< ORIG_AREA
<< std::endl
<< "ORIG_PERI = "
<< ORIG_PERI
<< std::endl;
LOGGING.close();
}
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING
<< "ORIG_TL = "
<< ORIG_TL
<< std::endl
<< "ORIG_BR = "
<< ORIG_BR
<< std::endl;
LOGGING.close();
}
// vector <int> outplus = test_edges(in_frame, contours[largest_contour_index]);
//
// int edge_top = 0;
// int edge_bot = 0;
// int edge_lef = 0;
// int edge_rig = 0;
//
// if ((abs(outplus[0]) > EDGETHRESH) || (abs(outplus[1]) > EDGETHRESH)) {
// if ((outplus[0] > 0) || (outplus[0] < 0)) {
// vector <int> local_edge = edge_width(contours[largest_contour_index]);
// edge_top = local_edge[0];
// edge_bot = local_edge[1];
// }
// if ((outplus[1] > 0) || (outplus[1] < 0)) {
// vector <int> local_edge = edge_height(contours[largest_contour_index]);
// edge_lef = local_edge[0];
// edge_rig = local_edge[1];
// }
// }
/*
// Open the outfile to append list of major ellipses
std::ofstream outell;
outell.open(ELLIPSEDATA, std::ios_base::app);
outell
<< framecnt
<< ","
<< box.x + (box.width/2)
<< ","
<< box.y + (box.height/2)
<< ","
<< box.width
<< ","
<< box.height
<< ","
<< box.area()
<< ","
<< edge_top
<< ","
<< edge_bot
<< ","
<< edge_lef
<< ","
<< edge_rig
<< std::endl;
outell.close();*/
// return in_frame;
return 0;
}
/**
* This function finds the largest contour (presumably the edge of the moon) and attempts to center
* the cropped image based on the centroid of the contour. It calls corner_matching in cases where
* the centroid is not an appropriate method for centering. Data from this ellipse are stored in
* the ellipse.csv file. A small portion of the edge of the moon contour is removed to keep out the
* noisest portions. Stores modified in_frame to HNC_FRAME global
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param framecnt int of nth frame retrieved by program
* @return status
*/
static int halo_noise_and_center(Mat in_frame, int framecnt) {
Mat temp_frame;
// Do a first pass/rough crop
if (initial_crop(in_frame.clone(), framecnt)) {
return 1;
}
in_frame = IC_FRAME;
// Make sure the black of night stays black so we can get the edge of the moon
threshold(in_frame.clone(), temp_frame, BLACKOUT_THRESH, 255, THRESH_TOZERO);
vector <vector<Point>> contours = contours_only(temp_frame);
int largest = largest_contour(contours);
Rect box = boundingRect(contours[largest]);
int edge_top = 0;
int edge_bot = 0;
int edge_lef = 0;
int edge_rig = 0;
int te_ret = touching_edges(in_frame, contours[largest]);
if (te_ret > 0) {
// if ((abs(outplus[0]) > EDGETHRESH) || (abs(outplus[1]) > EDGETHRESH)) {
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "Activating Corner Matching" << std::endl;
LOGGING.close();
}
vector <int> outplus = test_edges(in_frame, contours[largest], te_ret);
in_frame = shift_frame(in_frame, outplus[0], outplus[1]);
if ((outplus[0] > 0) || (outplus[0] < 0)) {
vector <int> local_edge = edge_width(contours[largest]);
edge_top = local_edge[0];
edge_bot = local_edge[1];
}
if ((outplus[1] > 0) || (outplus[1] < 0)) {
vector <int> local_edge = edge_height(contours[largest]);
edge_lef = local_edge[0];
edge_rig = local_edge[1];
}
} else if (te_ret == 0) {
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING << "Centering Traditionally" << std::endl;
LOGGING.close();
}
// Traditional centering
in_frame = traditional_centering(in_frame.clone(), contours, largest, box);
} else {
std::cerr << "WARNING: Returned improper value when testing touching edges" << std::endl;
}
// Find largest contour box on cropped frame
box_finder(in_frame, true);
box = BF_BOX;
// write that data to our boxes file.
box_data(box, framecnt);
// Open the outfile to append list of major ellipses
std::ofstream outell;
outell.open(ELLIPSEDATA, std::ios_base::app);
outell
<< framecnt
<< ","
<< box.x + (box.width/2)
<< ","
<< box.y + (box.height/2)
<< ","
<< box.width
<< ","
<< box.height
<< ","
<< box.area()
<< ","
<< edge_top
<< ","
<< edge_bot
<< ","
<< edge_lef
<< ","
<< edge_rig
<< std::endl;
outell.close();
HNC_FRAME = in_frame;
return 0;
}
/**
* This is a helper function to handle terminal signals. This shuts down the various forks properly
* when an interrupt is caught.
*
* @param signum signal number passed to this function. Only handles 2.
*/
void signal_callback_handler(int signum) {
if (signum == 2) {
std::cerr << "Caught ctrl+c interrupt signal: " << std::endl;
}
// Terminate program
SIG_ALERT = signum;
return;
}
/**
* This function masks out the edges of the input frame based on the contour. The maskwidth determines
* how much to mask out.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param contour OpenCV Point vectors of int-int point contour edges. Use the output from "bigone"
* here.
* @param maskwidth
* @return in_frame The modified in_frame from the input params
*/
static Mat apply_dynamic_mask(Mat in_frame, vector <Point> contour, int maskwidth) {
vector <vector <Point>> contours;
contours.push_back(contour);
drawContours(in_frame, contours, 0, 0, maskwidth, LINE_8);
return in_frame;
}
/**
* This function returns the index of the largest contour in a list of contours so it can be accessed
* in future functions.
*
* @param contours vector of OpenCV vectors of int-int point contour edges
* @return largest_contour_index integer index of the largest contour in a vector of contour vectors
*/
static int largest_contour(vector <vector<Point>> contours) {
int largest_contour_index = -1;
int largest_area = 0;
// Finds the largest contour in the "canny_output" of the input frame
for( size_t i = 0; i< contours.size(); i++ ) {
double area = contourArea(contours[i]);
if (area > largest_area) {
largest_area = area;
largest_contour_index = i;
}
}
return largest_contour_index;
}
/**
* This function returns the contours from an image. It really only needs to exist because
* repeatedly declaring the unused hierarchy is tedious.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @return vector of int-int OpenCV Point vectors for each contour detected in the in_frame
*/
static vector <vector<Point>> contours_only(Mat in_frame) {
vector <vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(in_frame, contours, hierarchy, RETR_TREE, CHAIN_APPROX_NONE);
return contours;
}
/**
* This function finds the bounding box for the largest contour and reports on its properties. Stores
* OpenCV Rect object bounding the largest contour (presumably the moon) to global BF_BOX.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @return status
*/
static int box_finder(Mat in_frame, bool do_thresh) {
// Make sure the black of night stays black so we can get the edge of the moon
if (do_thresh) {
threshold(in_frame.clone(), in_frame, BLACKOUT_THRESH, 255, THRESH_TOZERO);
}
vector <vector<Point>> contours = contours_only(in_frame);
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING
<< "Number of detected contours in ellipse frame: "
<< contours.size()
<< std::endl;
LOGGING.close();
}
if (contours.size() < 1) {
return 1;
}
int largest_contour_index = largest_contour(contours);
// Find the bounding box for the large contour
BF_BOX = boundingRect(contours[largest_contour_index]);
return 0;
}
/**
*
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param framecnt int of nth frame retrieved by program
* @return status
*/
static int box_data(Rect box, int framecnt) {
if (OUTPUT_FRAMES && TIGHT_CROP) {
std::ofstream outfile;
outfile.open(BOXDATA, std::ios_base::app);
outfile
<< framecnt << ","
<< box.tl().x << ","
<< box.tl().y << ","
<< box.br().x << ","
<< box.br().y << ","
<< box.x << ","
<< box.y << ","
<< box.width << ","
<< box.height << ","
<< box.area() << std::endl;
outfile.close();
}
return 0;
}
/**
* This is a helper function called using -h in terminal.
*
* @param name
* @return status
*/
static int show_usage(string name) {
std::cerr << "Usage: " << " <option(s)> \t\tSOURCES\tDescription\n"
<< "Options:\n"
<< "\t-h,--help\t\t\tShow this help message\n"
<< "\t-v,--version\t\t\tPrint version info to STDOUT\n"
<< "\t-i,--input\t\tINPUT\tSpecify path to input video\n"
<< "\t-c,--config-file \tINPUT\tSpecify config file (default settings.cfg)\n"
<< "\t-osf,--osf-path \tINPUT\tSpeify path to osf video\n"
<< std::endl;
return 0;
}
/**
* Finds the largest contour within the frame after masking. Called from main thread to prevent waste
* of CPU time for each tier.
*
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @return bigone vector of cv Points representing the largest frame in the image
*/
static vector <Point> qhe_bigone(Mat in_frame) {
GaussianBlur(in_frame.clone(), in_frame,
Size(QHE_GB_KERNEL_X, QHE_GB_KERNEL_Y),
QHE_GB_SIGMA_X,
QHE_GB_SIGMA_Y,
BORDER_DEFAULT
);
threshold(in_frame.clone(), in_frame, 1, 255, THRESH_BINARY);
vector <vector <Point>> local_contours = contours_only(in_frame);
int largest_contour_index = largest_contour(local_contours);
if (largest_contour_index < 0) {
vector <Point> empty;
empty.push_back(Point(-1, -1));
return empty;
} else {
vector <Point> bigone = local_contours[largest_contour_index];
return bigone;
}
}
/**
* This function removes contours which are near to the edge of the moon halo. This is a quiet kind
* of masking which does not alter the image, rather it quietly makes contours in violation
* `disappear'. The distance from the moon edge which is to be masked is determined by QHE_WIDTH
* from settings.cfg.
*
* @param contours vector of OpenCV vectors of int-int point contour edges
* @param bigone vector of Opencv Points representing the largest contour from qhe_bigone
* @return out_contours vector of OpenCV int-int Point vectors representing valid contours
*/
static vector <vector<Point>> quiet_halo_elim(vector <vector<Point>> contours, vector <Point> bigone) {
float distance;
vector <vector<Point>> out_contours;
bool caught_mask = false;
for (size_t i = 0; i < contours.size(); i++) {
caught_mask = false;
// Skip the big one
// if (i == largest_contour_index) {
// continue;
// }
Moments M = moments(contours[i]);
int x_cen = (M.m10/M.m00);
int y_cen = (M.m01/M.m00);
if ((x_cen < 0) || (y_cen < 0)) {
x_cen = contours[i][0].x;
y_cen = contours[i][0].y;
}
for (size_t j = 0; j < bigone.size(); j++) {
distance = sqrt(pow((x_cen - bigone[j].x), 2) + pow((y_cen - bigone[j].y), 2));
if (distance < QHE_WIDTH) {
caught_mask = true;
break;
}
}
if (!caught_mask) {
out_contours.push_back(contours[i]);
}
}
return out_contours;
}
/**
* This is the first pass to detect valid contours in a frame. The parameters of the function are
* set in the T1 section of settings.cfg. Contours are detected based on a relatively strict OpenCV
* adaptiveThreshold function. These should be gauranteed "hits".
*
* @param framecnt int of nth frame retrieved by program
* @param in_frame OpenCV matrix image, 16-bit single depth format
* @param bigone vector of Opencv Points representing the largest contour from qhe_bigone
* @return status
*/
int tier_one(int framecnt, Mat in_frame, vector <Point> bigone) {
Point2f center;
float radius;
float bigradius = 0;
std::ofstream outfile;
adaptiveThreshold(in_frame.clone(), in_frame,
T1_AT_MAX,
ADAPTIVE_THRESH_GAUSSIAN_C,
THRESH_BINARY_INV,
T1_AT_BLOCKSIZE,
T1_AT_CONSTANT
);
// Apply dynamic mask
in_frame = apply_dynamic_mask(in_frame.clone(), bigone, T1_DYMASK);
vector <vector<Point>> contours = contours_only(in_frame);
if (contours.size() > 1) {
contours = quiet_halo_elim(contours, bigone);
if (DEBUG_COUT) {
LOGGING.open(LOGOUT, std::ios_base::app);
LOGGING
<< "Number of contours in tier 1 pass for frame "
<< framecnt
<< ": "
<< contours.size()
<< std::endl;
LOGGING.close();
}
int largest_contour_index = largest_contour(contours);
if (largest_contour_index > -1) {
minEnclosingCircle(contours[largest_contour_index], center, bigradius);
}
outfile.open(TIER1FILE, std::ios_base::app);
// Cycle through the contours
for (auto vec : contours) {
// Greater than one includes lunar ellipse