-
Notifications
You must be signed in to change notification settings - Fork 1
/
cvcalibinit3.cpp
2462 lines (2061 loc) · 87.2 KB
/
cvcalibinit3.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
/************************************************************************************\
This is improved variant of chessboard corner detection algorithm that
uses a graph of connected quads. It is based on the code contributed
by Vladimir Vezhnevets and Philip Gruebele.
Here is the copyright notice from the original Vladimir's code:
===============================================================
The algorithms developed and implemented by Vezhnevets Vldimir
aka Dead Moroz ([email protected])
See http://graphics.cs.msu.su/en/research/calibration/opencv.html
for detailed information.
Reliability additions and modifications made by Philip Gruebele.
<a href="mailto:[email protected]">[email protected]</a>
His code was adapted for use with low resolution and omnidirectional cameras
by Martin Rufli during his Master Thesis under supervision of Davide Scaramuzza, at the ETH Zurich. Further enhancements include:
- Increased chance of correct corner matching.
- Corner matching over all dilation runs.
If you use this code, please cite the following articles:
1. Scaramuzza, D., Martinelli, A. and Siegwart, R. (2006), A Toolbox for Easily Calibrating Omnidirectional Cameras, Proceedings of the IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS 2006), Beijing, China, October 2006.
2. Scaramuzza, D., Martinelli, A. and Siegwart, R., (2006). "A Flexible Technique for Accurate Omnidirectional Camera Calibration and Structure from Motion", Proceedings of IEEE International Conference of Vision Systems (ICVS'06), New York, January 5-7, 2006.
3. Rufli, M., Scaramuzza, D., and Siegwart, R. (2008), Automatic Detection of Checkerboards on Blurred and Distorted Images, Proceedings of the IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS 2008), Nice, France, September 2008.
\************************************************************************************/
//===========================================================================
// CODE STARTS HERE
//===========================================================================
// Include files
#include <opencv.hpp>
//#include <opencv2/core/internal.hpp>
#include <opencv2/core/core.hpp>
#include <time.h>
#include <fstream>
using namespace std;
using std::ifstream;
// Defines
#define MAX_CONTOUR_APPROX 7
//Ming #define VIS 1
#define VIS 0
// Turn on visualization
#define TIMER 0 // Elapse the function duration times
// Definition Contour Struct
typedef struct CvContourEx
{
CV_CONTOUR_FIELDS()
int counter;
}
CvContourEx;
// Definition Corner Struct
typedef struct CvCBCorner
{
CvPoint2D32f pt; // X and y coordinates
int row; // Row and column of the corner
int column; // in the found pattern
bool needsNeighbor; // Does the corner require a neighbor?
int count; // number of corner neighbors
struct CvCBCorner* neighbors[4]; // pointer to all corner neighbors
}
CvCBCorner;
// Definition Quadrangle Struct
// This structure stores information about the chessboard quadrange
typedef struct CvCBQuad
{
int count; // Number of quad neihbors
int group_idx; // Quad group ID
float edge_len; // Smallest side length^2
CvCBCorner *corners[4]; // Coordinates of quad corners
struct CvCBQuad *neighbors[4]; // Pointers of quad neighbors
bool labeled; // Has this corner been labeled?
}
CvCBQuad;
//===========================================================================
// FUNCTION PROTOTYPES
//===========================================================================
static int icvGenerateQuads( CvCBQuad **quads, CvCBCorner **corners,
CvMemStorage *storage, CvMat *image, int flags, int dilation,
bool firstRun );
static void mrFindQuadNeighbors2( CvCBQuad *quads, int quad_count, int dilation);
static int mrAugmentBestRun( CvCBQuad *new_quads, int new_quad_count, int new_dilation,
CvCBQuad **old_quads, int old_quad_count, int old_dilation );
static int icvFindConnectedQuads( CvCBQuad *quads, int quad_count, CvCBQuad **quad_group,
int group_idx,
CvMemStorage* storage, int dilation );
static void mrLabelQuadGroup( CvCBQuad **quad_group, int count, CvSize pattern_size,
bool firstRun );
static void mrCopyQuadGroup( CvCBQuad **temp_quad_group, CvCBQuad **out_quad_group,
int count );
static int icvCleanFoundConnectedQuads( int quad_count, CvCBQuad **quads,
CvSize pattern_size );
static int mrWriteCorners( CvCBQuad **output_quads, int count, CvSize pattern_size,
int min_number_of_corners );
//===========================================================================
// MAIN FUNCTION
//===========================================================================
int cvFindChessboardCorners3( const void* arr, CvSize pattern_size,
CvPoint2D32f* out_corners, int* out_corner_count,
int min_number_of_corners )
{
//START TIMER
#if TIMER
ofstream FindChessboardCorners2;
time_t start_time = clock();
#endif
// PART 0: INITIALIZATION
//-----------------------------------------------------------------------
// Initialize variables
int flags = 1; // not part of the function call anymore!
int max_count = 0;
int max_dilation_run_ID = -1;
const int min_dilations = 1;
const int max_dilations = 6;
int found = 0;
CvMat* norm_img = 0;
CvMat* thresh_img = 0;
CvMat* thresh_img_save = 0;
CvMemStorage* storage = 0;
CvCBQuad *quads = 0;
CvCBQuad **quad_group = 0;
CvCBCorner *corners = 0;
CvCBCorner **corner_group = 0;
CvCBQuad **output_quad_group = 0;
// debug trial. Martin Rufli, 28. Ocober, 2008
int block_size = 0;
// Create error message file
ofstream error("cToMatlab/error.txt");
// Set openCV function name and label the function start
CV_FUNCNAME( "cvFindChessBoardCornerGuesses2" );
__CV_BEGIN__;
// Further initializations
int quad_count, group_idx, dilations;
CvMat stub, *img = (CvMat*)arr;
// Read image from input
CV_CALL( img = cvGetMat( img, &stub ));
// Error handling, write error message to error.txt
if( CV_MAT_DEPTH( img->type ) != CV_8U || CV_MAT_CN( img->type ) == 2 )
{
error << "Only 8-bit grayscale or color images are supported" << endl;
error.close();
return -1;
}
if( pattern_size.width < 2 || pattern_size.height < 2 )
{
error << "Pattern should have at least 2x2 size" << endl;
error.close();
return -1;
}
if( pattern_size.width > 127 || pattern_size.height > 127 )
{
error << "Pattern should not have a size larger than 127 x 127" << endl;
error.close();
return -1;
}
/*
if( pattern_size.width != pattern_size.height )
{
error << "In this implementation only square sized checker boards are supported" << endl;
error.close();
return -1;
}
*/
if( !out_corners )
{
error << "Null pointer to corners encountered" << endl;
error.close();
return -1;
}
// Create memory storage
CV_CALL( storage = cvCreateMemStorage(0) );
CV_CALL( thresh_img = cvCreateMat( img->rows, img->cols, CV_8UC1 ));
CV_CALL( thresh_img_save = cvCreateMat( img->rows, img->cols, CV_8UC1 ));
// Image histogramm normalization and
// BGR to Grayscale image conversion (if applicable)
// MARTIN: Set to "false"
if( CV_MAT_CN(img->type) != 1 || (flags & CV_CALIB_CB_NORMALIZE_IMAGE) )
{
CV_CALL( norm_img = cvCreateMat( img->rows, img->cols, CV_8UC1 ));
if( CV_MAT_CN(img->type) != 1 )
{
CV_CALL( cvCvtColor( img, norm_img, CV_BGR2GRAY ));
img = norm_img;
}
if(false)
{
cvEqualizeHist( img, norm_img );
img = norm_img;
}
}
// EVALUATE TIMER
#if TIMER
float time0_1 = (float) (clock() - start_time) / CLOCKS_PER_SEC;
FindChessboardCorners2.open("timer/FindChessboardCorners2.txt", ofstream::app);
FindChessboardCorners2 << "Time 0.1 for cvFindChessboardCorners2 was " << time0_1 << " seconds." << endl;
#endif
// For image binarization (thresholding)
// we use an adaptive threshold with a gaussian mask
// ATTENTION: Gaussian thresholding takes MUCH more time than Mean thresholding!
block_size = cvRound(MIN(img->cols,img->rows)*0.2)|1;
cvAdaptiveThreshold( img, thresh_img, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY, block_size, 0 );
cvCopy( thresh_img, thresh_img_save);
// PART 1: FIND LARGEST PATTERN
//-----------------------------------------------------------------------
// Checker patterns are tried to be found by dilating the background and
// then applying a canny edge finder on the closed contours (checkers).
// Try one dilation run, but if the pattern is not found, repeat until
// max_dilations is reached.
for( dilations = min_dilations; dilations <= max_dilations; dilations++ )
{
// Calling "cvCopy" again is much faster than rerunning "cvAdaptiveThreshold"
cvCopy( thresh_img_save, thresh_img);
// EVALUATE TIMER
#if TIMER
float time0_2 = (float) (clock() - start_time) / CLOCKS_PER_SEC;
FindChessboardCorners2 << "Time 0.2 for cvFindChessboardCorners2 was " << time0_2 << " seconds." << endl;
#endif
//VISUALIZATION--------------------------------------------------------------
#if VIS
cvNamedWindow( "Original Image", 1 );
cvShowImage( "Original Image", img);
//cvSaveImage("pictureVis/OrigImg.png", img);
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
// MARTIN's Code
// Use both a rectangular and a cross kernel. In this way, a more
// homogeneous dilation is performed, which is crucial for small,
// distorted checkers. Use the CROSS kernel first, since its action
// on the image is more subtle
IplConvKernel *kernel1 = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_CROSS,NULL);
IplConvKernel *kernel2 = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_RECT,NULL);
if (dilations >= 1)
cvDilate( thresh_img, thresh_img, kernel1, 1);
if (dilations >= 2)
cvDilate( thresh_img, thresh_img, kernel2, 1);
if (dilations >= 3)
cvDilate( thresh_img, thresh_img, kernel1, 1);
if (dilations >= 4)
cvDilate( thresh_img, thresh_img, kernel2, 1);
if (dilations >= 5)
cvDilate( thresh_img, thresh_img, kernel1, 1);
if (dilations >= 6)
cvDilate( thresh_img, thresh_img, kernel2, 1);
// EVALUATE TIMER
#if TIMER
float time0_3 = (float) (clock() - start_time) / CLOCKS_PER_SEC;
FindChessboardCorners2 << "Time 0.3 for cvFindChessboardCorners2 was " << time0_3 << " seconds." << endl;
#endif
//VISUALIZATION--------------------------------------------------------------
#if VIS
cvNamedWindow( "After adaptive Threshold (and Dilation)", 1 );
cvShowImage( "After adaptive Threshold (and Dilation)", thresh_img);
//cvSaveImage("pictureVis/afterDilation.png", thresh_img);
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
// In order to find rectangles that go to the edge, we draw a white
// line around the image edge. Otherwise FindContours will miss those
// clipped rectangle contours. The border color will be the image mean,
// because otherwise we risk screwing up filters like cvSmooth()
cvRectangle( thresh_img, cvPoint(0,0), cvPoint(thresh_img->cols-1,
thresh_img->rows-1), CV_RGB(255,255,255), 3, 8);
// Generate quadrangles in the following function
// "quad_count" is the number of cound quadrangles
CV_CALL( quad_count = icvGenerateQuads( &quads, &corners, storage, thresh_img, flags, dilations, true ));
if( quad_count <= 0 )
continue;
// EVALUATE TIMER
#if TIMER
float time0_4 = (float) (clock() - start_time) / CLOCKS_PER_SEC;
FindChessboardCorners2 << "Time 0.4 for cvFindChessboardCorners2 was " << time0_4 << " seconds." << endl;
#endif
//VISUALIZATION--------------------------------------------------------------
#if VIS
cvNamedWindow( "all found quads per dilation run", 1 );
IplImage* imageCopy2 = cvCreateImage( cvGetSize(thresh_img), 8, 1 );
IplImage* imageCopy22 = cvCreateImage( cvGetSize(thresh_img), 8, 3 );
cvCopy( thresh_img, imageCopy2);
cvCvtColor( imageCopy2, imageCopy22, CV_GRAY2BGR );
for( int kkk = 0; kkk < quad_count; kkk++ )
{
CvCBQuad* print_quad = &quads[kkk];
CvPoint pt[4];
pt[0].x = (int)print_quad->corners[0]->pt.x;
pt[0].y = (int)print_quad->corners[0]->pt.y;
pt[1].x = (int)print_quad->corners[1]->pt.x;
pt[1].y = (int)print_quad->corners[1]->pt.y;
pt[2].x = (int)print_quad->corners[2]->pt.x;
pt[2].y = (int)print_quad->corners[2]->pt.y;
pt[3].x = (int)print_quad->corners[3]->pt.x;
pt[3].y = (int)print_quad->corners[3]->pt.y;
cvLine( imageCopy22, pt[0], pt[1], CV_RGB(255,255,0), 1, 8 );
cvLine( imageCopy22, pt[1], pt[2], CV_RGB(255,255,0), 1, 8 );
cvLine( imageCopy22, pt[2], pt[3], CV_RGB(255,255,0), 1, 8 );
cvLine( imageCopy22, pt[3], pt[0], CV_RGB(255,255,0), 1, 8 );
}
cvShowImage( "all found quads per dilation run", imageCopy22);
//cvSaveImage("pictureVis/allFoundQuads.png", imageCopy22);
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
// The following function finds and assigns neighbor quads to every
// quadrangle in the immediate vicinity fulfilling certain
// prerequisites
CV_CALL( mrFindQuadNeighbors2( quads, quad_count, dilations));
//VISUALIZATION--------------------------------------------------------------
#if VIS
cvNamedWindow( "quads with neighbors", 1 );
IplImage* imageCopy3 = cvCreateImage( cvGetSize(thresh_img), 8, 3 );
cvCopy( imageCopy22, imageCopy3);
CvPoint pt;
int scale = 0;
int line_type = CV_AA;
CvScalar color = {{0,0,255}};
for( int kkk = 0; kkk < quad_count; kkk++ )
{
CvCBQuad* print_quad2 = &quads[kkk];
for( int kkkk = 0; kkkk < 4; kkkk++ )
{
if( print_quad2->neighbors[kkkk] )
{
pt.x = (int)(print_quad2->corners[kkkk]->pt.x);
pt.y = (int)(print_quad2->corners[kkkk]->pt.y);
cvCircle( imageCopy3, pt, 3, color, 1, line_type, scale);
}
}
}
cvShowImage( "quads with neighbors", imageCopy3);
//cvSaveImage("pictureVis/allFoundNeighbors.png", imageCopy3);
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
// Allocate memory
CV_CALL( quad_group = (CvCBQuad**)cvAlloc( sizeof(quad_group[0]) * quad_count));
CV_CALL( corner_group = (CvCBCorner**)cvAlloc( sizeof(corner_group[0]) * quad_count*4 ));
// The connected quads will be organized in groups. The following loop
// increases a "group_idx" identifier.
// The function "icvFindConnectedQuads assigns all connected quads
// a unique group ID.
// If more quadrangles were assigned to a given group (i.e. connected)
// than are expected by the input variable "pattern_size", the
// function "icvCleanFoundConnectedQuads" erases the surplus
// quadrangles by minimizing the convex hull of the remaining pattern.
for( group_idx = 0; ; group_idx++ )
{
int count;
CV_CALL( count = icvFindConnectedQuads( quads, quad_count, quad_group, group_idx, storage, dilations ));
if( count == 0 )
break;
CV_CALL( count = icvCleanFoundConnectedQuads( count, quad_group, pattern_size ));
// MARTIN's Code
// To save computational time, only proceed, if the number of
// found quads during this dilation run is larger than the
// largest previous found number
if( count >= max_count)
{
// set max_count to its new value
max_count = count;
max_dilation_run_ID = dilations;
// The following function labels all corners of every quad
// with a row and column entry.
// "count" specifies the number of found quads in "quad_group"
// with group identifier "group_idx"
// The last parameter is set to "true", because this is the
// first function call and some initializations need to be
// made.
mrLabelQuadGroup( quad_group, max_count, pattern_size, true );
//VISUALIZATION--------------------------------------------------------------
#if VIS
// display all corners in INCREASING ROW AND COLUMN ORDER
cvNamedWindow( "Corners in increasing order", 1 );
IplImage* imageCopy11 = cvCreateImage( cvGetSize(thresh_img), 8, 3 );
cvCopy( imageCopy22, imageCopy11);
// Assume min and max rows here, since we are outside of the
// relevant function
int min_row = -15;
int max_row = 15;
int min_column = -15;
int max_column = 15;
for(int i = min_row; i <= max_row; i++)
{
for(int j = min_column; j <= max_column; j++)
{
for(int k = 0; k < count; k++)
{
for(int l = 0; l < 4; l++)
{
if( ((quad_group[k])->corners[l]->row == i) && ((quad_group[k])->corners[l]->column == j) )
{
// draw the row and column numbers
char str[255];
sprintf(str,"%i/%i",i,j);
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.2, 0.2, 0, 1);
CvPoint ptt;
ptt.x = (int) quad_group[k]->corners[l]->pt.x;
ptt.y = (int) quad_group[k]->corners[l]->pt.y;
// Mark central corners with a different color than
// border corners
if ((quad_group[k])->corners[l]->needsNeighbor == false)
{
cvPutText(imageCopy11, str, ptt, &font, CV_RGB(0,255,0));
}
else
{
cvPutText(imageCopy11, str, ptt, &font, CV_RGB(255,0,0));
}
cvShowImage( "Corners in increasing order", imageCopy11);
//cvSaveImage("pictureVis/CornersIncreasingOrder.tif", imageCopy11);
//cvWaitKey(0);
}
}
}
}
}
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
// Allocate memory
CV_CALL( output_quad_group = (CvCBQuad**)cvAlloc( sizeof(output_quad_group[0]) * ((pattern_size.height+2) * (pattern_size.width+2)) ));
// The following function copies every member of "quad_group"
// to "output_quad_group", because "quad_group" will be
// overwritten during the next loop pass.
// "output_quad_group" is a true copy of "quad_group" and
// later used for output
mrCopyQuadGroup( quad_group, output_quad_group, max_count );
}
}
// Free the allocated variables
cvFree( &quads );
cvFree( &corners );
}
// EVALUATE TIMER
#if TIMER
float time1 = (float) (clock() - start_time) / CLOCKS_PER_SEC;
FindChessboardCorners2.open("timer/FindChessboardCorners2.txt", ofstream::app);
FindChessboardCorners2 << "Time 1 for cvFindChessboardCorners2 was " << time1 << " seconds." << endl;
#endif
// If enough corners have been found already, then there is no need for PART 2 ->EXIT
found = mrWriteCorners( output_quad_group, max_count, pattern_size, min_number_of_corners);
if (found == -1 || found == 1)
exit(0);
// PART 2: AUGMENT LARGEST PATTERN
//-----------------------------------------------------------------------
// Instead of saving all found quads of all dilation runs from PART 1, we
// just recompute them again, but skipping the dilation run which
// produced the maximum number of found quadrangles.
// In essence the first section of PART 2 is identical to the first
// section of PART 1.
for( dilations = max_dilations; dilations >= min_dilations; dilations-- )
{
//if(max_dilation_run_ID == dilations)
// continue;
// Calling "cvCopy" again is much faster than rerunning "cvAdaptiveThreshold"
cvCopy( thresh_img_save, thresh_img);
IplConvKernel *kernel1 = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_CROSS,NULL);
IplConvKernel *kernel2 = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_RECT,NULL);
if (dilations >= 1)
cvDilate( thresh_img, thresh_img, kernel1, 1);
if (dilations >= 2)
cvDilate( thresh_img, thresh_img, kernel2, 1);
if (dilations >= 3)
cvDilate( thresh_img, thresh_img, kernel1, 1);
if (dilations >= 4)
cvDilate( thresh_img, thresh_img, kernel2, 1);
if (dilations >= 5)
cvDilate( thresh_img, thresh_img, kernel1, 1);
if (dilations >= 6)
cvDilate( thresh_img, thresh_img, kernel2, 1);
cvRectangle( thresh_img, cvPoint(0,0), cvPoint(thresh_img->cols-1,
thresh_img->rows-1), CV_RGB(255,255,255), 3, 8);
//VISUALIZATION--------------------------------------------------------------
#if VIS
cvNamedWindow( "PART2: Starting Point", 1 );
IplImage* imageCopy23 = cvCreateImage( cvGetSize(thresh_img), 8, 3 );
cvCvtColor( thresh_img, imageCopy23, CV_GRAY2BGR );
CvPoint *pt = new CvPoint[4];
for( int kkk = 0; kkk < max_count; kkk++ )
{
CvCBQuad* print_quad2 = output_quad_group[kkk];
for( int kkkk = 0; kkkk < 4; kkkk++ )
{
pt[kkkk].x = (int) print_quad2->corners[kkkk]->pt.x;
pt[kkkk].y = (int) print_quad2->corners[kkkk]->pt.y;
}
// draw a filled polygon
cvFillConvexPoly ( imageCopy23, pt, 4, CV_RGB(255*0.1,255*0.25,255*0.6));
}
// indicate the dilation run
char str[255];
sprintf(str,"Dilation Run No.: %i",dilations);
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 2);
//cvPutText(imageCopy23, str, cvPoint(20,20), &font, CV_RGB(0,255,0));
cvShowImage( "PART2: Starting Point", imageCopy23);
cvSaveImage("pictureVis/part2Start.png", imageCopy23);
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
CV_CALL( quad_count = icvGenerateQuads( &quads, &corners, storage, thresh_img, flags, dilations, false ));
if( quad_count <= 0 )
continue;
//VISUALIZATION--------------------------------------------------------------
#if VIS
//draw on top of previous image
for( int kkk = 0; kkk < quad_count; kkk++ )
{
CvCBQuad* print_quad = &quads[kkk];
CvPoint pt[4];
pt[0].x = (int)print_quad->corners[0]->pt.x;
pt[0].y = (int)print_quad->corners[0]->pt.y;
pt[1].x = (int)print_quad->corners[1]->pt.x;
pt[1].y = (int)print_quad->corners[1]->pt.y;
pt[2].x = (int)print_quad->corners[2]->pt.x;
pt[2].y = (int)print_quad->corners[2]->pt.y;
pt[3].x = (int)print_quad->corners[3]->pt.x;
pt[3].y = (int)print_quad->corners[3]->pt.y;
cvLine( imageCopy23, pt[0], pt[1], CV_RGB(255,0,0), 1, 8 );
cvLine( imageCopy23, pt[1], pt[2], CV_RGB(255,0,0), 1, 8 );
cvLine( imageCopy23, pt[2], pt[3], CV_RGB(255,0,0), 1, 8 );
cvLine( imageCopy23, pt[3], pt[0], CV_RGB(255,0,0), 1, 8 );
//compute center of print_quad
int x1 = (pt[0].x + pt[1].x)/2;
int y1 = (pt[0].y + pt[1].y)/2;
int x2 = (pt[2].x + pt[3].x)/2;
int y2 = (pt[2].y + pt[3].y)/2;
int x3 = (x1 + x2)/2;
int y3 = (y1 + y2)/2;
// indicate the quad number in the image
char str[255];
sprintf(str,"%i",kkk);
//CvFont font;
//cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1);
//cvPutText(imageCopy23, str, cvPoint(x3,y3), &font, CV_RGB(0,255,255));
}
for( int kkk = 0; kkk < max_count; kkk++ )
{
CvCBQuad* print_quad = output_quad_group[kkk];
CvPoint pt[4];
pt[0].x = (int)print_quad->corners[0]->pt.x;
pt[0].y = (int)print_quad->corners[0]->pt.y;
pt[1].x = (int)print_quad->corners[1]->pt.x;
pt[1].y = (int)print_quad->corners[1]->pt.y;
pt[2].x = (int)print_quad->corners[2]->pt.x;
pt[2].y = (int)print_quad->corners[2]->pt.y;
pt[3].x = (int)print_quad->corners[3]->pt.x;
pt[3].y = (int)print_quad->corners[3]->pt.y;
//compute center of print_quad
int x1 = (pt[0].x + pt[1].x)/2;
int y1 = (pt[0].y + pt[1].y)/2;
int x2 = (pt[2].x + pt[3].x)/2;
int y2 = (pt[2].y + pt[3].y)/2;
int x3 = (x1 + x2)/2;
int y3 = (y1 + y2)/2;
// indicate the quad number in the image
char str[255];
sprintf(str,"%i",kkk);
//CvFont font;
//cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1);
//cvPutText(imageCopy23, str, cvPoint(x3,y3), &font, CV_RGB(0,0,0));
}
cvShowImage( "PART2: Starting Point", imageCopy23);
cvSaveImage("pictureVis/part2StartAndNewQuads.png", imageCopy23);
cvWaitKey(0);
#endif
//END------------------------------------------------------------------------
// MARTIN's Code
// The following loop is executed until no more newly found quads
// can be matched to one of the border corners of the largest found
// pattern from PART 1.
// The function "mrAugmentBestRun" tests whether a quad can be linked
// to the existng pattern.
// The function "mrLabelQuadGroup" then labels the newly added corners
// with the respective row and column entries.
int feedBack = -1;
while ( feedBack == -1)
{
feedBack = mrAugmentBestRun( quads, quad_count, dilations,
output_quad_group, max_count, max_dilation_run_ID );
//VISUALIZATION--------------------------------------------------------------
#if VIS
if( feedBack == -1)
{
CvCBQuad* remember_quad;
for( int kkk = max_count; kkk < max_count+1; kkk++ )
{
CvCBQuad* print_quad = output_quad_group[kkk];
remember_quad = print_quad;
CvPoint pt[4];
pt[0].x = (int)print_quad->corners[0]->pt.x;
pt[0].y = (int)print_quad->corners[0]->pt.y;
pt[1].x = (int)print_quad->corners[1]->pt.x;
pt[1].y = (int)print_quad->corners[1]->pt.y;
pt[2].x = (int)print_quad->corners[2]->pt.x;
pt[2].y = (int)print_quad->corners[2]->pt.y;
pt[3].x = (int)print_quad->corners[3]->pt.x;
pt[3].y = (int)print_quad->corners[3]->pt.y;
cvLine( imageCopy23, pt[0], pt[1], CV_RGB(255,0,0), 2, 8 );
cvLine( imageCopy23, pt[1], pt[2], CV_RGB(255,0,0), 2, 8 );
cvLine( imageCopy23, pt[2], pt[3], CV_RGB(255,0,0), 2, 8 );
cvLine( imageCopy23, pt[3], pt[0], CV_RGB(255,0,0), 2, 8 );
}
cvWaitKey(0);
// also draw the corner to which it is connected
// Remember it is not yet completely linked!!!
for( int kkk = 0; kkk < max_count; kkk++ )
{
CvCBQuad* print_quad = output_quad_group[kkk];
for( int kkkk = 0; kkkk < 4; kkkk++)
{
if(print_quad->neighbors[kkkk] == remember_quad)
{
CvPoint pt[4];
pt[0].x = (int)print_quad->corners[0]->pt.x;
pt[0].y = (int)print_quad->corners[0]->pt.y;
pt[1].x = (int)print_quad->corners[1]->pt.x;
pt[1].y = (int)print_quad->corners[1]->pt.y;
pt[2].x = (int)print_quad->corners[2]->pt.x;
pt[2].y = (int)print_quad->corners[2]->pt.y;
pt[3].x = (int)print_quad->corners[3]->pt.x;
pt[3].y = (int)print_quad->corners[3]->pt.y;
cvLine( imageCopy23, pt[0], pt[1], CV_RGB(255,0,0), 2, 8 );
cvLine( imageCopy23, pt[1], pt[2], CV_RGB(255,0,0), 2, 8 );
cvLine( imageCopy23, pt[2], pt[3], CV_RGB(255,0,0), 2, 8 );
cvLine( imageCopy23, pt[3], pt[0], CV_RGB(255,0,0), 2, 8 );
}
}
}
cvShowImage( "PART2: Starting Point", imageCopy23);
cvSaveImage("pictureVis/part2StartAndSelectedQuad.png", imageCopy23);
cvWaitKey(0);
}
#endif
//END------------------------------------------------------------------------
// if we have found a new matching quad
if (feedBack == -1)
{
// increase max_count by one
max_count = max_count + 1;
mrLabelQuadGroup( output_quad_group, max_count, pattern_size, false );
// write the found corners to output array
// Go to __CV_END__, if enough corners have been found
found = mrWriteCorners( output_quad_group, max_count, pattern_size, min_number_of_corners);
if (found == -1 || found == 1)
exit(0);
}
}
}
// "End of file" jump point
// After the command "exit(0)" the code jumps here
__CV_END__;
/*
// MARTIN:
found = mrWriteCorners( output_quad_group, max_count, pattern_size, min_number_of_corners);
*/
// If a linking problem was encountered, throw an error message
if( found == -1 )
{
error << "While linking the corners a problem was encountered. No corner sequence is returned. " << endl;
error.close();
return -1;
}
// Release allocated memory
cvReleaseMemStorage( &storage );
cvReleaseMat( &norm_img );
cvReleaseMat( &thresh_img );
cvFree( &quads );
cvFree( &corners );
cvFree( &quad_group );
cvFree( &corner_group );
cvFree( &output_quad_group );
error.close();
// EVALUATE TIMER
#if TIMER
float time3 = (float) (clock() - start_time) / CLOCKS_PER_SEC;
FindChessboardCorners2 << "Time 3 for cvFindChessboardCorners2 was " << time3 << " seconds." << endl;
FindChessboardCorners2.close();
#endif
// Return found
// Found can have the values
// -1 -> Error or corner linking problem, see error.txt for more information
// 0 -> Not enough corners were found
// 1 -> Enough corners were found
return found;
}
//===========================================================================
// ERASE OVERHEAD
//===========================================================================
// If we found too many connected quads, remove those which probably do not
// belong.
static int
icvCleanFoundConnectedQuads( int quad_count, CvCBQuad **quad_group, CvSize pattern_size )
{
CvMemStorage *temp_storage = 0;
CvPoint2D32f *centers = 0;
CV_FUNCNAME( "icvCleanFoundConnectedQuads" );
__CV_BEGIN__;
CvPoint2D32f center = CvPoint2D32f(0,0);
int i, j, k;
// Number of quads this pattern should contain
int count = ((pattern_size.width + 1)*(pattern_size.height + 1) + 1)/2;
// If we have more quadrangles than we should, try to eliminate duplicates
// or ones which don't belong to the pattern rectangle. Else go to the end
// of the function
if( quad_count <= count )
exit(0);
// Create an array of quadrangle centers
CV_CALL( centers = (CvPoint2D32f *)cvAlloc( sizeof(centers[0])*quad_count ));
CV_CALL( temp_storage = cvCreateMemStorage(0));
for( i = 0; i < quad_count; i++ )
{
CvPoint2D32f ci = CvPoint2D32f(0,0);
CvCBQuad* q = quad_group[i];
for( j = 0; j < 4; j++ )
{
CvPoint2D32f pt = q->corners[j]->pt;
ci.x += pt.x;
ci.y += pt.y;
}
ci.x *= 0.25f;
ci.y *= 0.25f;
// Centers(i), is the geometric center of quad(i)
// Center, is the center of all found quads
centers[i] = ci;
center.x += ci.x;
center.y += ci.y;
}
center.x /= quad_count;
center.y /= quad_count;
// If we have more quadrangles than we should, we try to eliminate bad
// ones based on minimizing the bounding box. We iteratively remove the
// point which reduces the size of the bounding box of the blobs the most
// (since we want the rectangle to be as small as possible) remove the
// quadrange that causes the biggest reduction in pattern size until we
// have the correct number
for( ; quad_count > count; quad_count-- )
{
double min_box_area = DBL_MAX;
int skip, min_box_area_index = -1;
CvCBQuad *q0, *q;
// For each point, calculate box area without that point
for( skip = 0; skip < quad_count; skip++ )
{
// get bounding rectangle
CvPoint2D32f temp = centers[skip];
centers[skip] = center;
CvMat pointMat = cvMat(1, quad_count, CV_32FC2, centers);
CvSeq *hull = cvConvexHull2( &pointMat, temp_storage, CV_CLOCKWISE, 1 );
centers[skip] = temp;
double hull_area = fabs(cvContourArea(hull, CV_WHOLE_SEQ));
// remember smallest box area
if( hull_area < min_box_area )
{
min_box_area = hull_area;
min_box_area_index = skip;
}
cvClearMemStorage( temp_storage );
}
q0 = quad_group[min_box_area_index];
// remove any references to this quad as a neighbor
for( i = 0; i < quad_count; i++ )
{
q = quad_group[i];
for( j = 0; j < 4; j++ )
{
if( q->neighbors[j] == q0 )
{
q->neighbors[j] = 0;
q->count--;
for( k = 0; k < 4; k++ )
if( q0->neighbors[k] == q )
{
q0->neighbors[k] = 0;
q0->count--;
break;
}
break;
}
}
}
// remove the quad by copying th last quad in the list into its place
quad_count--;
quad_group[min_box_area_index] = quad_group[quad_count];
centers[min_box_area_index] = centers[quad_count];
}
__CV_END__;
cvReleaseMemStorage( &temp_storage );
cvFree( ¢ers );
return quad_count;
}
//===========================================================================
// FIND COONECTED QUADS
//===========================================================================
static int
icvFindConnectedQuads( CvCBQuad *quad, int quad_count, CvCBQuad **out_group,
int group_idx, CvMemStorage* storage, int dilation )
{
//START TIMER
#if TIMER
ofstream FindConnectedQuads;
time_t start_time = clock();
#endif
// initializations
CvMemStorage* temp_storage = cvCreateChildMemStorage( storage );
CvSeq* stack = cvCreateSeq( 0, sizeof(*stack), sizeof(void*), temp_storage );
int i, count = 0;
// Scan the array for a first unlabeled quad
for( i = 0; i < quad_count; i++ )
{
if( quad[i].count > 0 && quad[i].group_idx < 0)
break;
}
// Recursively find a group of connected quads starting from the seed
// quad[i]
if( i < quad_count )
{
CvCBQuad* q = &quad[i];
cvSeqPush( stack, &q );
out_group[count++] = q;
q->group_idx = group_idx;
while( stack->total )
{
cvSeqPop( stack, &q );
for( i = 0; i < 4; i++ )
{
CvCBQuad *neighbor = q->neighbors[i];
// If he neighbor exists and the neighbor has more than 0
// neighbors and the neighbor has not been classified yet.
if( neighbor && neighbor->count > 0 && neighbor->group_idx < 0 )
{
cvSeqPush( stack, &neighbor );
out_group[count++] = neighbor;
neighbor->group_idx = group_idx;
}
}
}
}