-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcvfind.cpp
More file actions
8776 lines (7159 loc) · 360 KB
/
cvfind.cpp
File metadata and controls
8776 lines (7159 loc) · 360 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
/*
Copyright (c) 2023 Robert Charles Mahar
bob@muhlenberg.edu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Rev. 20231212_1559
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cstring>
#include <string>
#include <ctime>
#include <thread>
#include <mutex>
#include <numeric>
#include <future>
// #include <filesystem>
#include <unordered_set>
#if defined(__linux__)
// For non portable use of prctl(PR_SET_NAME, "name_here", 0, 0, 0);
#include <sys/prctl.h>
#include <unistd.h>
#endif
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/features2d.hpp"
// opencv placed all non open IP into opencv_contrib which may not be present.
#if defined(WITH_OPENCV_CONTRIB)
#include "opencv2/xfeatures2d.hpp"
#include "opencv2/line_descriptor.hpp"
#endif
// My only regrets with this codebase is that I cannot use emoji in comments. Lots of emoji.
using namespace std;
using namespace cv;
// opencv placed all non open IP into opencv_contrib which may not be present.
#if defined(__OPENCV_XFEATURES2D_HPP__)
using namespace cv::xfeatures2d;
using namespace cv::line_descriptor;
#endif
#define MAX_IMAGES 10000
#define MAX_CPS_PER_PAIR 10000
bool dotrace = false; // enable trace output
bool debug = false; // enable debug output
int loglevel = 1; // 0 - 2: terse, 3 - 5: verbose, 6 - 8: debug, > 8: trace
enum detectorType {
AKAZE = 0, // An entry for each detector algorithm
ORB,
BRISK,
CORNER,
GFTT,
LINE,
SEGMENT,
BLOB,
SURF,
SIFT,
DSIFT, // Dense SIFT, keypoints on a grid
PTO, // CPs imported from the input PTO
ALL, // A merged version of all, aka number of detectors
COUNT // Ordinal count of the number of detectors
};
vector<std::string> detectorName {
"AKAZE",
"ORB",
"BRISK",
"CORNER",
"GFTT",
"LINE",
"SEGMENT",
"BLOB",
"SURF",
"SIFT",
"DSIFT",
"PTO",
"ALL",
"COUNT" };
// Used to sort vector< Point2f >
struct p2fcomp_st{
bool operator() ( Point2f a, Point2f b ){
if ( a.y != b.y )
return a.y < b.y;
return a.x <= b.x ;
}
} p2fcomp;
// Used to sort vector< vector<int> > descending by the 1st element in the child vector
struct vvintcompd_st{
bool operator() ( vector<int> a, vector<int> b ){
return a[0] > b[0];
}
} vvintcompd;
struct ptoPoint {
double x;
double y;
};
/* is struct candidatePair
class ptoIndexPair {
public:
int idx1;
int idx2;
ptoIndexPair( int i_idx1, int i_idx2 ) { idx1 = i_idx1, idx2 = i_idx2; }
};
*/
struct ptoControlPoint {
int idx1; // source image index aka "n"
int idx2; // destination image index aka "N"
ptoPoint src; //
ptoPoint dst; //
ptoPoint vector; //
int line; // the line number in the .pto image, if any
double scalar; //
double slope; //
int detector; // when known
};
/* subsumed by ptoControlPoint
struct ptoCPEntry {
int idx1; // source image index aka "n"
int idx2; // destination image index aka "N"
ptoPoint src;
ptoPoint dst;
int line;
};
*/
int preScaleFactor = 1; // scale ( down sample ) input images and unscale on output.
std::mutex imageMutex[MAX_IMAGES]; // a mutex for each ptoImage in images[]
class ptoImage {
public:
std::mutex* mutex; // Pointer to a mutex
bool needed; // marked true when a pair is identified for image analysis
int rowStartHint; // Number of upvotes for this being the start of a row ( per shooting pattern )
int rowEndHint; // Number of upvotes for this being the end of a row ( per shooting pattern )
int w; // width aka xSize from the PTO file
int h; // height aka ySize from the PTO file
int idx; // Image index
std::string filename; // Filename of the image as found in the PTO file.
// std::filesystem::path path; // ( this is a path object, not just the parent directory )
int groupRoot; // The image's root group
std::vector<int> candidates; // Images this images may be paired with, possibly
std::vector<int> neighbors; // Image neighbors passing all validation steps
Mat img; // the original image, cached in memory
Mat imgGray; // grey scale version of img
//
// Each ptoImage maintains its own cache of features detected for each detector type. The detector deposits
// features into the respective structure ( here ). The matchers for an individual image pair deposits matches into
// the ptoImagePair structure. This allows for all of this data to be available during analysis.
//
#if defined(__OPENCV_XFEATURES2D_HPP__)
std::vector<std::vector<KeyLine>> keylines = std::vector<std::vector<KeyLine>>(detectorType::ALL);
#endif
std::vector<std::vector<KeyPoint>> keypoints = std::vector<std::vector<KeyPoint>>(detectorType::ALL);
std::vector<Mat> descriptors = std::vector<Mat>(detectorType::ALL);
// Constructor used during importing referenced images from a PTO
ptoImage( std::string i_filename, int i_idx )
{
ptoImage();
filename = i_filename;
idx = i_idx;
needed = false;
}
// Constructor used for an uninitiallized ptoImage
ptoImage() { w = h = idx = groupRoot = rowStartHint = rowEndHint = 0; needed = false; mutex = &imageMutex[idx]; };
// loads the image and makes various useful copies of it
void load()
{
lock();
img = imread(filename);
if( preScaleFactor == 1 )
{
cvtColor(img, imgGray, cv::COLOR_BGR2GRAY);
}
else
{
Mat scaled;
// specify fx and fy and let the function compute the destination image size.
resize(img, scaled, Size(), (float)1 / (float)preScaleFactor, (float)1 / (float)preScaleFactor, INTER_LINEAR );
cvtColor(scaled, imgGray, cv::COLOR_BGR2GRAY);
}
// img = imgGray;
unlock();
}
// Caller manages concurrency, as when loading an image or populating features / keypoints
void lock() { mutex->lock(); }
void unlock() { mutex->unlock(); }
}; // ptoImage
// Get the center of mass ( COM ) in terms of image coordinates
Point2f COM( std::vector<Point2f> pv )
{
Point2f com = Point2f(0,0);
for( int i = 0; i < pv.size(); i++ )
{
com.x += pv[i].x;
com.y += pv[i].y;
}
if( pv.size() > 0 )
{
com.x = com.x / pv.size();
com.y = com.y / pv.size();
}
return com;
}
// Return a comma separated string of ranges, e.g. {1,3,5,7,8,9,10,...18,100,106} --> "1,3,5,7-18,100,106"
std::string vi2csv( std::vector<int> vi )
{
// handle edge cases
if( vi.size() == 0 ) return "";
if( vi.size() == 1 ) return to_string( vi[0] );
if( vi.size() == 2 ) return to_string( vi[0] ) + "," + to_string( vi[1] );
std::string retval = "";
int idx = 0;
int cur = 0;
while( idx < vi.size() )
{
retval += to_string(vi[idx] ); // add vi[idx]
cur = idx;
// while vi[idx+1] INCREMENTS by one
while( idx + 1 < vi.size() && vi[idx] == vi[idx+1] - 1 )
{
idx++;
}
if( idx > cur )
{
retval += "-" + to_string( vi[idx] );
}
idx++;
if( idx < vi.size() ) retval += ",";
}
return retval;
}
// Global to hold all ptoImage objects referenced in the PTO
std::vector<ptoImage> images{}; // Holds a class instance for each image
// A point pad serves as a scratch pad for holding control point clouds for a pair of images.
// The image pair object maintains lists of point pads, generally the most recent is used
// others are kept for troubleshooting purposes.
class ptoPointPad {
public:
std::string padName;
std::vector<Point2f> points1; // image1 point array
std::vector<Point2f> points2; // image2 point array
std::vector<int> pointType; // detectorType ENUM
std::vector<int> lineIdx; // If in-memory PTO line number if imported from PTO
std::vector<float> distance; // "Distance" between corresponding control points cionfirmed by homography
cv::Rect rect1; // rect containing points1
cv::Rect rect2; // rect containing points2
cv::RotatedRect minAreaRect1; // minAreaRect contating points1
cv::RotatedRect minAreaRect2; // minAreaRect contating points2
cv::Point2f com1; // center of mass for points1
cv::Point2f com2; // center of mass for points2
float comscalar; // scalar distance between centers of mass
float comslope; // slope of line passing through centers of mass
int idx1 = 0; // source image index aka "n"
int idx2 = 0; // destination image index aka "N"
int deltaX, deltaY; // the X and Y difference between com1 and com2
Mat h; // current homography matrix, if any
void refresh()
{
if( idx1 == idx2 ) cout << "FATAL: Uninitiallized pointPad structure." << std::endl;
// update bounding rectangles
if( points1.size() > 0 ) rect1 = boundingRect( points1 );
if( points2.size() > 0 ) rect2 = boundingRect( points2 );
if( points1.size() > 0 ) minAreaRect1 = minAreaRect( points1 );
if( points2.size() > 0 ) minAreaRect2 = minAreaRect( points2 );
com1 = COM( points1 );
com2 = COM( points2 );
deltaX = com2.x - com1.x;
deltaY = com2.y - com1.y;
comscalar=(float)sqrt( ( deltaX * deltaX ) + ( deltaY * deltaY ) );
if( deltaX == 0 )
{
comslope=(float)deltaY * (float)1000000; // instead of divide by zero, multiply by 1000000
}
else
{
comslope=(float)( (float)deltaY / (float)deltaX );
}
}
int size() { return pointType.size(); }
// copies bare minimum data to prime the structure to revieve filtered data
void prime( ptoPointPad *pp )
{
idx1 = pp->idx1;
idx2 = pp->idx2;
padName = pp->padName;
return;
}
std::vector<std::string> dump()
{
std::vector<std::string> retval;
std::string s;
if( idx1 == idx2 ) cout << "FATAL: Uninitiallized pointPad structure." << std::endl;
// Loop through each match, apply a quadrant based filter
for( size_t i = 0; i < size(); i++ )
{
int xSize = images[idx1].img.cols;
int ySize = images[idx1].img.rows;
float x1, y1, x2, y2, dx, dy, scalar, slope;
std::string notes = "";
x1 = points1[i].x;
x2 = points2[i].x;
y1 = points1[i].y;
y2 = points2[i].y;
dx = x2 - x1;
dy = y2 - y1;
scalar=sqrt( ( dx * dx ) + ( dy * dy ) );
if( dx == 0 )
{
slope=dy * 1000000; // instead of divide by zero, multiply by 1000000
}
else
{
slope=dy / dx;
}
s = "Raw Matches: [" + to_string(idx1) + "] --> [" + to_string(idx2) + "] " \
+ detectorName[ pointType[i] ] + " ( " + to_string( x1 ) + ", " + to_string( y1 ) \
+ " ) <---> ( " + to_string( x2 ) + ", " + to_string( y2 ) + " ) Scalar: " \
+ to_string( scalar ) + " Slope: " + to_string( slope ) + " PTO_Line: " + to_string( lineIdx[i] ) ;
retval.push_back( s );
}
return retval;
}
};
//
// Cheesy class to keep benchmarks
//
class benchmarkEpoc {
public:
std::string name;
std::chrono::time_point<std::chrono::system_clock> time;
benchmarkEpoc( std::string i_name, std::chrono::time_point<std::chrono::system_clock> i_time )
{ name = i_name; time = i_time; }
};
//
// The "idea" of an image pair. Includes all feature, match, control point, and homography info for a pair
// only idx1 < idx2 is valid. This reflects the way PTO files maintain their control points.
// If homography projected in the reverse order is needed, that can be accomplished by inversion of the H matrix.
//
class ptoImgPair {
public:
int idx1 = 0 ; // source image index aka "n"
int idx2 = 0 ; // destination image index aka "N"
std::vector<benchmarkEpoc> benchmarks;
std::vector<ptoControlPoint> points{};
ptoControlPoint cpAve;
int groupRoot; // image number of the first image in the group set to itself by default.
std::vector<std::vector<int>> loops; // Loops tried ( all pairs get a copy of all loop results )
std::vector<float> loopError; // Error for loop[n]
int votesL2, votesL1, votesL0, votesLB;
int repairScalar = 0; // For rework, this scalar overrides any detected scalar and is used for final homography
ptoImgPair() { idx1 = idx2 = groupRoot = votesL2 = votesL1 = votesL0 = votesLB = 0; }; // An invalid unitialized state
// matches [ detector type ] [ scratch_pad ] [ match_idx ]
// we probabaly don't need a locking mechanism as access will be pair wise, single threaded for write
// detectorType::COUNT is the ordinal number of detector slots we need to have, including the synthetic
// "ALL" detector.
std::vector<std::vector<std::string>> padName = \
std::vector<std::vector<std::string>>(detectorType::COUNT);
std::vector<std::vector<std::vector<DMatch>>> matches = \
std::vector<std::vector<std::vector<DMatch>>>(detectorType::COUNT);
std::vector<std::vector<std::vector<ptoControlPoint>>> cps = \
std::vector<std::vector<std::vector<ptoControlPoint>>>(detectorType::COUNT);
// point pads for trial homography
std::vector<ptoPointPad> trialPointPad;
// Unified points1 and points2 and detectorType for the point
std::vector<ptoPointPad> pointPad;
// current homography matrix, if any
Mat h;
// list of strings proposed edits to Hugin PTO file
std::vector<std::string> newCPlist;
// ( Probabaly need something for control line )
// return index to a new matches, padname, and cps vector for the specified detector.
int newMatchPad( int i_detector, std::string i_padName )
{
if( idx1 == idx2 ) cout << "FATAL: Uninitiallized ptoImagePair structure." << std::endl;
if( loglevel > 8 ) cout << "TRACE: newMatchPad( " << i_detector << ", '" << i_padName << "' )" << std::endl;
padName[i_detector].push_back( i_padName );
std::vector<DMatch> newmatches;
matches[i_detector].push_back( newmatches );
std::vector<ptoControlPoint> newcps;
cps[i_detector].push_back( newcps );
if( matches[i_detector].size() != cps[i_detector].size() || matches[i_detector].size() != padName[i_detector].size() )
cout << "FATAL: newMatchPad(" << i_detector << ", '" << i_padName
<< "'): cps.size() != matches.size() != padName.size()" << std::endl;
return cps[i_detector].size() -1; // return index, not count. Also cps, padname, matches have same size.
}
int currentMatchPad( int i_detector )
{
if( loglevel > 8 ) cout << "TRACE: currentMatchPad( " << i_detector << " )" << std::endl;
if( cps[i_detector].size() == 0 )
return newMatchPad( i_detector, "First Match Pad" );
return (cps[i_detector].size() - 1);
}
// Accumulates all cps[detector=0...N] and updates the cps pad specified, returns total points accumulated
int refreshPointPad( )
{
if( idx1 == idx2 )
{
cout << "FATAL: refreshPointPad() called with uninitialized ptoImagePair structure. idx1 == idx2 == " << idx1 << std::endl;
cout.flush();
loglevel = 10;
}
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ..." << std::endl;
int pp = currentPointPad(); // returns the index of the current point pad or a new one if none exists
// clear the point pad
pointPad[pp].points1.clear();
pointPad[pp].points2.clear();
pointPad[pp].pointType.clear();
pointPad[pp].lineIdx.clear();
pointPad[pp].distance.clear();
/*
// Remove all entries NOT imported from the PTO file ( else we loose the lineIdx values )
for( int i=0; i < pointPad[pp].size() > 0; i++ )
{
if( pointPad[pp].pointType[i] != detectorType::PTO )
{
pointPad[pp].points1.erase( pointPad[pp].points1.begin() + i );
pointPad[pp].points2.erase( pointPad[pp].points2.begin() + i );
pointPad[pp].pointType.erase( pointPad[pp].pointType.begin() + i );
pointPad[pp].lineIdx.erase( pointPad[pp].lineIdx.begin() + i );
pointPad[pp].distance.erase( pointPad[pp].distance.begin() + i );
// at this point i points at what was i+1, so decrement i so we examine that one nect time
i--;
}
}
*/
for( int detector=0; detector < detectorType::ALL; detector++ )
{
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... extract points for " << detectorName[detector] << std::endl;
// Look at the current pad for this detector
int pad = currentMatchPad(detector);
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... extract points for " << detectorName[detector]
<< " MatchPad " << pad << " Matches: " << matches[detector][pad].size()
<< std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... Image Pair: " << idx1 << ":" << idx2 << std::endl;
// For true detectors ...
for( int i = 0; detector != detectorType::PTO && i < matches[detector][pad].size(); i++ )
{
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... extract points " << i << " for " << detectorName[detector] << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... KP:" << images[idx1].keypoints.size()
<< ":" << images[idx2].keypoints.size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... KP:" << images[idx1].keypoints[detector].size()
<< ":" << images[idx2].keypoints[detector].size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... matches.size():" << matches.size()
<< ":" << matches.size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... matches[].size():" << matches[detector].size()
<< ":" << matches[detector].size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... matches[][].size():" << matches[detector][pad].size()
<< ":" << matches[detector][pad].size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... Matches Pair:" << matches[detector][pad][i].queryIdx
<< ":" << matches[detector][pad][i].trainIdx << std::endl;
Point2f pt1 = images[idx1].keypoints[detector][ matches[detector][pad][i].queryIdx ].pt;
Point2f pt2 = images[idx2].keypoints[detector][ matches[detector][pad][i].trainIdx ].pt;
int detType = detector;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... Extracted points" << pt1 << ":" << pt2
<< " for detector " << detType << std::endl;
pointPad[pp].points1.push_back( pt1 );
pointPad[pp].points2.push_back( pt2 );
pointPad[pp].pointType.push_back( detType );
pointPad[pp].lineIdx.push_back( 0 ); // no PTO line
pointPad[pp].distance.push_back( 0 );
}
// For points extracted from the PTO ...
for( int i = 0; detector == detectorType::PTO && cps[detector].size() > 0 && i < cps[detector][pad].size(); i++ )
{
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... extract point " << i << " for " << detectorName[detector] << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... cps.size():" << cps.size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... cps[" << detector << "].size():" << cps[detector].size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... cps[" << detector << "][" << pad << "].size():"
<< cps[detector][pad].size() << std::endl;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... cps[" << detector << "][" << pad << "][" << i << "]:" << std::endl;
Point2f pt1, pt2;
int line;
pt1.x = cps[detector][pad][i].src.x;
pt1.y = cps[detector][pad][i].src.y;
pt2.x = cps[detector][pad][i].dst.x;
pt2.y = cps[detector][pad][i].dst.y;
line = cps[detector][pad][i].line;
int detType = detector;
if( loglevel > 8 ) cout << "TRACE: refreshPointPad( ) ... Extracted points" << pt1 << ":" << pt2
<< " for detector " << detType << " PTO Line: " << line << std::endl;
// Detected control points from homography are added to the in memory PTO,
// so we only want ones where the detector type PTO. So cue the kludge.
pointPad[pp].points1.push_back( pt1 );
pointPad[pp].points2.push_back( pt2 );
pointPad[pp].pointType.push_back( detType );
pointPad[pp].lineIdx.push_back( line ); // no PTO line
pointPad[pp].distance.push_back( 0 );
}
} // for each detector
if( loglevel > 8 ) cout << "... refreshPointPad( ) = " << pointPad[pp].points1.size() << std::endl;
return pointPad[pp].points1.size();
}
// return current Point Pad, make one if needed
int currentPointPad( )
{
if( loglevel > 8 ) cout << "TRACE: currentPointPad( ) ..." << std::endl;
if( loglevel > 8 ) cout << "TRACE: currentPointPad( ) pointPad.size()=" << pointPad.size() << std::endl;
if( pointPad.size() == 0 )
{
newPointPad( "Default pointPad for " + to_string( idx1 ) + ":" + to_string( idx2 ) );
}
if( loglevel > 8 ) cout << " ... currentPointPad( ) = " << pointPad.size() - 1 << std::endl;
return pointPad.size() - 1;
}
// make an empty point pad
int newPointPad( std::string i_padName )
{
if( loglevel > 8 ) cout << "TRACE: newPointPad( '" << i_padName << "' ) ..." << std::endl;
ptoPointPad foo;
foo.padName = i_padName;
foo.idx1 = idx1;
foo.idx2 = idx2;
pointPad.push_back( foo );
if( loglevel > 8 ) cout << "... newPointPad( '" << i_padName << "' ) = " << pointPad.size() - 1 << std::endl;
return pointPad.size() - 1;
}
}; // ptoImgPair
// Represents a loop homography trial indicating both the pairwise links in image indices aas well as the H matrix
class ptoTrialPermutation {
public:
std::vector<int> chain; // An image chain ( list indices of images[] array )
std::vector<int> trialChain; // The indices of each trialPointPad for each image pair in the chain
std::vector<cv::Mat> hChain; // The homography chain
Point2f errorPoint; // the error values returned by transitiveError( )
float error; // the scalar magnitide of the error.
}; // ptoTrialPermutation
// Useful Macros ...
#define RECT2STR(R) "Corner: (" + to_string( R.x ) + ", " + to_string( R.y ) + ") Size: ("\
+ to_string( R.width ) + ", " + to_string( R.height ) + ")"
#define BENCHMARK(B,T) (B).push_back(benchmarkEpoc( (T), std::chrono::high_resolution_clock::now() ) )
#define IMGLOG sout << "alignImage( " << left0padint(idx1, 4) << " --> " << left0padint(idx2, 4) << " ): "
#define OPTIONBOOL(O,V,X) \
if ( ! parsed && j < argc && 0 == strcmp(argv[j], #O) ) \
{ \
(V) = (X); \
if( loglevel > 6 ) sout << "Parsed argv[" << j << "]='" << argv[j] \
<< "' option ( " << #O << " ). Setting " << #V << " to " << (V) << std::endl; \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
parsed = true; \
}
#define OPTIONINT(O,V,MIN,MAX) \
if ( ! parsed && j < argc && 0 == strcmp(argv[j], #O) ) \
{ \
std::string theoption = argv[j]; \
std::string theparm; \
int thenum = 0; \
bool inbounds = false; \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
if( j < argc && 0 != strncmp(argv[j], "-", (size_t) 1) ) \
{ \
theparm = argv[j]; \
thenum = stoi( theparm ); \
if( thenum >= (MIN) && thenum <= MAX ) \
{ \
(V) = thenum; \
if( loglevel > 6 ) sout << "Parsed argv[" << j << "]='" << theoption << "' with value '" << theparm \
<< "' option ( " << #O << " ). Range [" << (MIN) << "," << (MAX) << "]" \
<< " Setting " << #V << " to " << (V) << std::endl; \
} \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
} \
if( thenum < (MIN) || thenum > (MAX) ) \
{ \
sout << "ERROR: option " << theoption << " should be between " << (MIN) << " and " << (MAX) << std::endl; \
return 1; \
} \
parsed = true; \
}
#define OPTIONINTCSV(O,V,MIN,MAX) \
if ( ! parsed && j < argc && 0 == strcmp(argv[j], #O) ) \
{ \
std::string theoption = argv[j]; \
std::string theparm; \
std::vector<int> thenums; \
bool inbounds = false; \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
if( j < argc && 0 != strncmp(argv[j], "-", (size_t) 1) ) \
{ \
theparm = argv[j]; \
if( theparm == "all" ) theparm = to_string(MIN) + "-" + to_string((MAX) - 1); \
if( theparm.size() > 0 && theparm[theparm.size()-1] == '-' ) theparm += to_string((MAX) - 1); \
if( theparm.size() > 0 && theparm[0] == '-' ) theparm.insert(0, to_string((MIN))); \
thenums = findIntList( theparm ); \
if( thenums.size() >= (MIN) && thenums.size() <= MAX ) \
{ \
(V) = thenums; \
if( loglevel > 6 ) sout << "Parsed argv[" << j << "]='" << theoption << "' with value '" << theparm \
<< "' option ( " << #O << " ). Range [" << (MIN) << "," << (MAX) << "]" \
<< " Setting " << #V << " to " << vi2csv(V) << std::endl; \
} \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
} \
if( thenums.size() < (MIN) || thenums.size() > (MAX) ) \
{ \
sout << "ERROR: option " << theoption << " list size should be between " << (MIN) << " and " << (MAX) << std::endl; \
return 1; \
} \
parsed = true; \
}
#define OPTIONFLOAT(O,V,MIN,MAX) \
if ( ! parsed && j < argc && 0 == strcmp(argv[j], #O) ) \
{ \
std::string theoption = argv[j]; \
std::string theparm; \
float thenum = 0; \
bool inbounds = false; \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
if( j < argc && 0 != strncmp(argv[j], "-", (size_t) 1) ) \
{ \
theparm = argv[j]; \
thenum = stof( theparm ); \
if( thenum >= (MIN) && thenum <= MAX ) \
{ \
(V) = thenum; \
if( loglevel > 6 ) sout << "Parsed argv[" << j << "]='" << theoption << "' with value '" << theparm \
<< "' option ( " << #O << " ). Range [" << (MIN) << "," << (MAX) << "]" \
<< " Setting " << #V << " to " << (V) << std::endl; \
} \
for(int i=1; i<argc; ++i) \
argv[i] = argv[i+1]; \
--argc; \
} \
if( thenum < (MIN) || thenum > (MAX) ) \
{ \
sout << "ERROR: option " << theoption << " should be between " << (MIN) << " and " << (MAX) << std::endl; \
return 1; \
} \
parsed = true; \
}
//
// - - - - - - - - - Parallel Sort Template - - - - - - - - -- - - - - - -
//
/* DoDo: Remove: Hopelessly broken
template <typename Q>
void swap(size_t i, size_t j, std::vector<Q>& v) {
std::swap(v[i], v[j]);
}
template <typename Comp, typename Vec, typename... Vecs>
void parallel_sort(const Comp& comp, Vec& keyvec, Vecs&... vecs) {
(assert(keyvec.size() == vecs.size()), ...);
std::vector<size_t> index(keyvec.size());
std::iota(index.begin(), index.end(), 0);
std::sort(index.begin(), index.end(),
[&](size_t a, size_t b) { return comp(keyvec[a], keyvec[b]); });
for (size_t i = 0; i < index.size(); i++) {
if (index[i] != i) {
(swap(index[i], i, keyvec), ..., swap(index[i], i, vecs));
std::swap(index[index[i]], index[i]);
}
}
}
*/
template< typename T, typename U >
std::vector<T> sortVecAByVecB( std::vector<T> & a, std::vector<U> & b ){
// zip the two vectors (A,B)
std::vector<std::pair<T,U>> zipped(a.size());
for( size_t i = 0; i < a.size(); i++ ) zipped[i] = std::make_pair( a[i], b[i] );
// sort according to B
std::sort(zipped.begin(), zipped.end(), []( auto & lop, auto & rop ) { return lop.second < rop.second; });
// extract sorted A
std::vector<T> sorted;
std::transform(zipped.begin(), zipped.end(), std::back_inserter(sorted), []( auto & pair ){ return pair.first; });
return sorted;
}
template<typename T>
void appendVector(vector<T>& v1, vector<T>& v2)
{
v1.insert(v1.end(), v2.begin(), v2.end());
}
template<typename T, typename ...Args>
void appendVector(vector<T>& v1, vector<T>& v2, Args... args)
{
v1.insert(v1.end(), v2.begin(), v2.end());
appendVector(v1, args...);
}
//
// - - - - - - - - Global MUTEXes for various concurrent processes- - - - - - - - -
//
std::mutex logger_guard;
std::mutex newcplist_guard;
//
// Allow output of vectors in the format {_,_,_,....,_}
//
template <typename S>
ostream& operator<<(ostream& os,
const vector<S>& vector)
{
// Printing the vector as {_,_,_,...,}
os << "{";
for ( int i=0; i < vector.size(); i++ )
{
auto element = vector[i];
os << element;
if( i+1 != vector.size() ) os << ","; // add comma if not final element
}
os << "}";
return os;
}
//
// - - - - - - - - - - - Tee for logging to a file - - - - - - - - - - - -
//
class soutstream
{
public:
std::ofstream coss;
std::string facility = " (main) ";
// this is the type of std::cout
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
// this is the function signature of std::endl
typedef CoutType& (*StandardEndLine)(CoutType&);
// define an operator<< to take in std::endl
soutstream& operator<<(StandardEndLine manip)
{
// call the function, but we cannot return it's value
manip(std::cout);
if(coss.is_open())
{
coss << "\n";
coss.flush();
}
return *this;
}
};
// std::mutex logger_guard; // see globals...
template <class T>
soutstream& operator<< (soutstream& st, T val)
{
logger_guard.lock();
if(st.coss.is_open())
{
st.coss << val;
st.coss.flush();
}
std::cout << val;
cout.flush();
logger_guard.unlock();
return st;
}
//
// Horrific Date String Format
//
string GetDateTime()
{
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
int yearval=(now->tm_year + 1900);
int monthval=(now->tm_mon + 1);
int dayval=(now->tm_mday);
int hourval=(now->tm_hour);
int minval=(now->tm_min);
int secval=(now->tm_sec);
char c_year[12];
sprintf(c_year, "%d", yearval);
char c_month[12];
sprintf(c_month, "%d", monthval);
char c_day[12];
sprintf(c_day, "%d", dayval);
char c_hour[12];
sprintf(c_hour, "%d", hourval);
char c_min[12];
sprintf(c_min, "%d", minval);
char c_sec[12];
sprintf(c_sec, "%d", secval);
string output = "";
output += c_year;
// output += "-";
output += c_month;
// output += "-";
output += c_day;
output += "_";
output += c_hour;
// output += "-";
output += c_min;
// output += "-";
output += c_sec;
return output;
}
//
// Instantiate the global Tee stream logger
//
soutstream sout;
// return -1 if a preceeds b, 1 if b preceeds a, or 0 if one or other not found
int StringOrder( std::string s, std::string a, std::string b )
{
std::size_t afound = s.find(a);
std::size_t bfound = s.find(b);
if( afound == bfound || afound == std::string::npos || bfound == std::string::npos )
return 0; // happens if both are std::string::npos
int diff = (int)afound - (int)bfound; // nagative if a before b
return abs( diff ) / diff; // returns -1 or +1
}
//
// imageIndexPair - The "idea" of a pair of image indices.
//
class imageIndexPair {
public:
int idx1;
int idx2;
bool operator == (const imageIndexPair &p)
{
if (idx1 == p.idx1 && idx1 == p.idx1)
return true;
return false;
}
friend std::ostream& operator<<(std::ostream& o, imageIndexPair const& i_iip)
{
o << "(" << i_iip.idx1 << ":" << i_iip.idx2 << ")";
return o;
}
};
//
// Global list of image pairs of interest - this is the punch list for image processing.
//
std::vector<imageIndexPair> candidatePairs; // a list of index pairs to process
//
// my own function to left pad a positive integer with zeros,
// because COBOL has been doing this since 1953.