forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalibinit.cpp
More file actions
2207 lines (1927 loc) · 72.7 KB
/
calibinit.cpp
File metadata and controls
2207 lines (1927 loc) · 72.7 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
//M*//////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
/************************************************************************************\
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 (vvp@graphics.cs.msu.ru)
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:pgruebele@cox.net">pgruebele@cox.net</a>
Some further improvements for detection of partially ocluded boards at non-ideal
lighting conditions have been made by Alex Bovyrin and Kurt Kolonige
\************************************************************************************/
/************************************************************************************\
This version adds a new and improved variant of chessboard corner detection
that works better in poor lighting condition. It is based on work from
Oliver Schreer and Stefano Masneri. This method works faster than the previous
one and reverts back to the older method in case no chessboard detection is
possible. Overall performance improves also because now the method avoids
performing the same computation multiple times when not necessary.
\************************************************************************************/
#include "precomp.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/calib3d/calib3d_c.h"
#include "circlesgrid.hpp"
#include <stdarg.h>
#include <vector>
using namespace cv;
using namespace std;
//#define ENABLE_TRIM_COL_ROW
//#define DEBUG_CHESSBOARD
#ifdef DEBUG_CHESSBOARD
static int PRINTF( const char* fmt, ... )
{
va_list args;
va_start(args, fmt);
return vprintf(fmt, args);
}
#else
#define PRINTF(...)
#endif
//=====================================================================================
// Implementation for the enhanced calibration object detection
//=====================================================================================
#define MAX_CONTOUR_APPROX 7
struct CvContourEx
{
CV_CONTOUR_FIELDS()
int counter;
};
//=====================================================================================
/// Corner info structure
/** This structure stores information about the chessboard corner.*/
struct CvCBCorner
{
CvPoint2D32f pt; // Coordinates of the corner
int row; // Board row index
int count; // Number of neighbor corners
struct CvCBCorner* neighbors[4]; // Neighbor corners
float meanDist(int *_n) const
{
float sum = 0;
int n = 0;
for( int i = 0; i < 4; i++ )
{
if( neighbors[i] )
{
float dx = neighbors[i]->pt.x - pt.x;
float dy = neighbors[i]->pt.y - pt.y;
sum += sqrt(dx*dx + dy*dy);
n++;
}
}
if(_n)
*_n = n;
return sum/MAX(n,1);
}
};
//=====================================================================================
/// Quadrangle contour info structure
/** This structure stores information about the chessboard quadrange.*/
struct CvCBQuad
{
int count; // Number of quad neighbors
int group_idx; // quad group ID
int row, col; // row and column of this quad
bool ordered; // true if corners/neighbors are ordered counter-clockwise
float edge_len; // quad edge len, in pix^2
// neighbors and corners are synced, i.e., neighbor 0 shares corner 0
CvCBCorner *corners[4]; // Coordinates of quad corners
struct CvCBQuad *neighbors[4]; // Pointers of quad neighbors
};
//=====================================================================================
#ifdef DEBUG_CHESSBOARD
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
static void SHOW(const std::string & name, Mat & img)
{
imshow(name, img);
while ((uchar)waitKey(0) != 'q') {}
}
static void SHOW_QUADS(const std::string & name, const Mat & img_, CvCBQuad * quads, int quads_count)
{
Mat img = img_.clone();
if (img.channels() == 1)
cvtColor(img, img, COLOR_GRAY2BGR);
for (int i = 0; i < quads_count; ++i)
{
CvCBQuad & quad = quads[i];
for (int j = 0; j < 4; ++j)
{
line(img, quad.corners[j]->pt, quad.corners[(j + 1) % 4]->pt, Scalar(0, 240, 0), 1, LINE_AA);
}
}
imshow(name, img);
while ((uchar)waitKey(0) != 'q') {}
}
#else
#define SHOW(...)
#define SHOW_QUADS(...)
#endif
//=====================================================================================
static int icvGenerateQuads( CvCBQuad **quads, CvCBCorner **corners,
CvMemStorage *storage, const Mat &image_, int flags, int *max_quad_buf_size);
static bool processQuads(CvCBQuad *quads, int quad_count, CvSize pattern_size, int max_quad_buf_size,
CvMemStorage * storage, CvCBCorner *corners, CvPoint2D32f *out_corners, int *out_corner_count, int & prev_sqr_size);
/*static int
icvGenerateQuadsEx( CvCBQuad **out_quads, CvCBCorner **out_corners,
CvMemStorage *storage, CvMat *image, CvMat *thresh_img, int dilation, int flags );*/
static void icvFindQuadNeighbors( CvCBQuad *quads, int quad_count );
static int icvFindConnectedQuads( CvCBQuad *quads, int quad_count,
CvCBQuad **quad_group, int group_idx,
CvMemStorage* storage );
static int icvCheckQuadGroup( CvCBQuad **quad_group, int count,
CvCBCorner **out_corners, CvSize pattern_size );
static int icvCleanFoundConnectedQuads( int quad_count,
CvCBQuad **quads, CvSize pattern_size );
static int icvOrderFoundConnectedQuads( int quad_count, CvCBQuad **quads,
int *all_count, CvCBQuad **all_quads, CvCBCorner **corners,
CvSize pattern_size, int max_quad_buf_size, CvMemStorage* storage );
static void icvOrderQuad(CvCBQuad *quad, CvCBCorner *corner, int common);
#ifdef ENABLE_TRIM_COL_ROW
static int icvTrimCol(CvCBQuad **quads, int count, int col, int dir);
static int icvTrimRow(CvCBQuad **quads, int count, int row, int dir);
#endif
static int icvAddOuterQuad(CvCBQuad *quad, CvCBQuad **quads, int quad_count,
CvCBQuad **all_quads, int all_count, CvCBCorner **corners, int max_quad_buf_size);
static void icvRemoveQuadFromGroup(CvCBQuad **quads, int count, CvCBQuad *q0);
static int icvCheckBoardMonotony( CvPoint2D32f* corners, CvSize pattern_size );
/***************************************************************************************************/
//COMPUTE INTENSITY HISTOGRAM OF INPUT IMAGE
static int icvGetIntensityHistogram( const Mat & img, std::vector<int>& piHist )
{
// sum up all pixel in row direction and divide by number of columns
for ( int j=0; j<img.rows; j++ )
{
const uchar * row = img.ptr(j);
for ( int i=0; i<img.cols; i++ )
{
piHist[row[i]]++;
}
}
return 0;
}
/***************************************************************************************************/
//SMOOTH HISTOGRAM USING WINDOW OF SIZE 2*iWidth+1
static int icvSmoothHistogram( const std::vector<int>& piHist, std::vector<int>& piHistSmooth, int iWidth )
{
int iIdx;
for ( int i=0; i<256; i++)
{
int iSmooth = 0;
for ( int ii=-iWidth; ii<=iWidth; ii++)
{
iIdx = i+ii;
if (iIdx > 0 && iIdx < 256)
{
iSmooth += piHist[iIdx];
}
}
piHistSmooth[i] = iSmooth/(2*iWidth+1);
}
return 0;
}
/***************************************************************************************************/
//COMPUTE FAST HISTOGRAM GRADIENT
static int icvGradientOfHistogram( const std::vector<int>& piHist, std::vector<int>& piHistGrad )
{
piHistGrad[0] = 0;
for ( int i=1; i<255; i++)
{
piHistGrad[i] = piHist[i-1] - piHist[i+1];
if ( abs(piHistGrad[i]) < 100 )
{
if ( piHistGrad[i-1] == 0)
piHistGrad[i] = -100;
else
piHistGrad[i] = piHistGrad[i-1];
}
}
return 0;
}
/***************************************************************************************************/
//PERFORM SMART IMAGE THRESHOLDING BASED ON ANALYSIS OF INTENSTY HISTOGRAM
static bool icvBinarizationHistogramBased( Mat & img )
{
CV_Assert(img.channels() == 1 && img.depth() == CV_8U);
int iCols = img.cols;
int iRows = img.rows;
int iMaxPix = iCols*iRows;
int iMaxPix1 = iMaxPix/100;
const int iNumBins = 256;
std::vector<int> piHistIntensity(iNumBins, 0);
std::vector<int> piHistSmooth(iNumBins, 0);
std::vector<int> piHistGrad(iNumBins, 0);
std::vector<int> piAccumSum(iNumBins, 0);
std::vector<int> piMaxPos(20, 0);
int iThresh = 0;
int iIdx;
int iWidth = 1;
icvGetIntensityHistogram( img, piHistIntensity );
// get accumulated sum starting from bright
piAccumSum[iNumBins-1] = piHistIntensity[iNumBins-1];
for ( int i=iNumBins-2; i>=0; i-- )
{
piAccumSum[i] = piHistIntensity[i] + piAccumSum[i+1];
}
// first smooth the distribution
icvSmoothHistogram( piHistIntensity, piHistSmooth, iWidth );
// compute gradient
icvGradientOfHistogram( piHistSmooth, piHistGrad );
// check for zeros
int iCntMaxima = 0;
for ( int i=iNumBins-2; (i>2) && (iCntMaxima<20); i--)
{
if ( (piHistGrad[i-1] < 0) && (piHistGrad[i] > 0) )
{
piMaxPos[iCntMaxima] = i;
iCntMaxima++;
}
}
iIdx = 0;
int iSumAroundMax = 0;
for ( int i=0; i<iCntMaxima; i++ )
{
iIdx = piMaxPos[i];
iSumAroundMax = piHistSmooth[iIdx-1] + piHistSmooth[iIdx] + piHistSmooth[iIdx+1];
if ( iSumAroundMax < iMaxPix1 && iIdx < 64 )
{
for ( int j=i; j<iCntMaxima-1; j++ )
{
piMaxPos[j] = piMaxPos[j+1];
}
iCntMaxima--;
i--;
}
}
if ( iCntMaxima == 1)
{
iThresh = piMaxPos[0]/2;
}
else if ( iCntMaxima == 2)
{
iThresh = (piMaxPos[0] + piMaxPos[1])/2;
}
else // iCntMaxima >= 3
{
// CHECKING THRESHOLD FOR WHITE
int iIdxAccSum = 0, iAccum = 0;
for (int i=iNumBins-1; i>0; i--)
{
iAccum += piHistIntensity[i];
// iMaxPix/18 is about 5,5%, minimum required number of pixels required for white part of chessboard
if ( iAccum > (iMaxPix/18) )
{
iIdxAccSum = i;
break;
}
}
int iIdxBGMax = 0;
int iBrightMax = piMaxPos[0];
// printf("iBrightMax = %d\n", iBrightMax);
for ( int n=0; n<iCntMaxima-1; n++)
{
iIdxBGMax = n+1;
if ( piMaxPos[n] < iIdxAccSum )
{
break;
}
iBrightMax = piMaxPos[n];
}
// CHECKING THRESHOLD FOR BLACK
int iMaxVal = piHistIntensity[piMaxPos[iIdxBGMax]];
//IF TOO CLOSE TO 255, jump to next maximum
if ( piMaxPos[iIdxBGMax] >= 250 && iIdxBGMax < iCntMaxima )
{
iIdxBGMax++;
iMaxVal = piHistIntensity[piMaxPos[iIdxBGMax]];
}
for ( int n=iIdxBGMax + 1; n<iCntMaxima; n++)
{
if ( piHistIntensity[piMaxPos[n]] >= iMaxVal )
{
iMaxVal = piHistIntensity[piMaxPos[n]];
iIdxBGMax = n;
}
}
//SETTING THRESHOLD FOR BINARIZATION
int iDist2 = (iBrightMax - piMaxPos[iIdxBGMax])/2;
iThresh = iBrightMax - iDist2;
PRINTF("THRESHOLD SELECTED = %d, BRIGHTMAX = %d, DARKMAX = %d\n", iThresh, iBrightMax, piMaxPos[iIdxBGMax]);
}
if ( iThresh > 0 )
{
for ( int jj=0; jj<iRows; jj++)
{
uchar * row = img.ptr(jj);
for ( int ii=0; ii<iCols; ii++)
{
if ( row[ii] < iThresh )
row[ii] = 0;
else
row[ii] = 255;
}
}
}
return true;
}
CV_IMPL
int cvFindChessboardCorners( const void* arr, CvSize pattern_size,
CvPoint2D32f* out_corners, int* out_corner_count,
int flags )
{
int found = 0;
CvCBQuad *quads = 0;
CvCBCorner *corners = 0;
cv::Ptr<CvMemStorage> storage;
CV_TRY
{
int k = 0;
const int min_dilations = 0;
const int max_dilations = 7;
if( out_corner_count )
*out_corner_count = 0;
Mat img = cvarrToMat((CvMat*)arr).clone();
if( img.depth() != CV_8U || (img.channels() != 1 && img.channels() != 3 && img.channels() != 4) )
CV_Error( CV_StsUnsupportedFormat, "Only 8-bit grayscale or color images are supported" );
if( pattern_size.width <= 2 || pattern_size.height <= 2 )
CV_Error( CV_StsOutOfRange, "Both width and height of the pattern should have bigger than 2" );
if( !out_corners )
CV_Error( CV_StsNullPtr, "Null pointer to corners" );
if (img.channels() != 1)
{
cvtColor(img, img, COLOR_BGR2GRAY);
}
Mat thresh_img_new = img.clone();
icvBinarizationHistogramBased( thresh_img_new ); // process image in-place
SHOW("New binarization", thresh_img_new);
if( flags & CV_CALIB_CB_FAST_CHECK)
{
//perform new method for checking chessboard using a binary image.
//image is binarised using a threshold dependent on the image histogram
if (checkChessboardBinary(thresh_img_new, pattern_size) <= 0) //fall back to the old method
{
if (checkChessboard(img, pattern_size) <= 0)
{
return found;
}
}
}
storage.reset(cvCreateMemStorage(0));
int prev_sqr_size = 0;
// Try our standard "1" dilation, but if the pattern is not found, iterate the whole procedure with higher dilations.
// This is necessary because some squares simply do not separate properly with a single dilation. However,
// we want to use the minimum number of dilations possible since dilations cause the squares to become smaller,
// making it difficult to detect smaller squares.
for( int dilations = min_dilations; dilations <= max_dilations; dilations++ )
{
if (found)
break; // already found it
//USE BINARY IMAGE COMPUTED USING icvBinarizationHistogramBased METHOD
dilate( thresh_img_new, thresh_img_new, Mat(), Point(-1, -1), 1 );
// So we can 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()...
rectangle( thresh_img_new, Point(0,0), Point(thresh_img_new.cols-1, thresh_img_new.rows-1), Scalar(255,255,255), 3, LINE_8);
int max_quad_buf_size = 0;
cvFree(&quads);
cvFree(&corners);
int quad_count = icvGenerateQuads( &quads, &corners, storage, thresh_img_new, flags, &max_quad_buf_size );
PRINTF("Quad count: %d/%d\n", quad_count, (pattern_size.width/2+1)*(pattern_size.height/2+1));
SHOW_QUADS("New quads", thresh_img_new, quads, quad_count);
if (processQuads(quads, quad_count, pattern_size, max_quad_buf_size, storage, corners, out_corners, out_corner_count, prev_sqr_size))
found = 1;
}
PRINTF("Chessboard detection result 0: %d\n", found);
// revert to old, slower, method if detection failed
if (!found)
{
if( flags & CV_CALIB_CB_NORMALIZE_IMAGE )
{
equalizeHist( img, img );
}
Mat thresh_img;
prev_sqr_size = 0;
PRINTF("Fallback to old algorithm\n");
const bool useAdaptive = flags & CV_CALIB_CB_ADAPTIVE_THRESH;
if (!useAdaptive)
{
// empiric threshold level
// thresholding performed here and not inside the cycle to save processing time
double mean = cv::mean(img).val[0];
int thresh_level = MAX(cvRound( mean - 10 ), 10);
threshold( img, thresh_img, thresh_level, 255, THRESH_BINARY );
}
//if flag CV_CALIB_CB_ADAPTIVE_THRESH is not set it doesn't make sense to iterate over k
int max_k = useAdaptive ? 6 : 1;
for( k = 0; k < max_k; k++ )
{
for( int dilations = min_dilations; dilations <= max_dilations; dilations++ )
{
if (found)
break; // already found it
// convert the input grayscale image to binary (black-n-white)
if (useAdaptive)
{
int block_size = cvRound(prev_sqr_size == 0
? MIN(img.cols, img.rows) * (k % 2 == 0 ? 0.2 : 0.1)
: prev_sqr_size * 2);
block_size = block_size | 1;
// convert to binary
adaptiveThreshold( img, thresh_img, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, block_size, (k/2)*5 );
if (dilations > 0)
dilate( thresh_img, thresh_img, Mat(), Point(-1, -1), dilations-1 );
}
else
{
dilate( thresh_img, thresh_img, Mat(), Point(-1, -1), 1 );
}
SHOW("Old binarization", thresh_img);
// So we can 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()...
rectangle( thresh_img, Point(0,0), Point(thresh_img.cols-1, thresh_img.rows-1), Scalar(255,255,255), 3, LINE_8);
int max_quad_buf_size = 0;
cvFree(&quads);
cvFree(&corners);
int quad_count = icvGenerateQuads( &quads, &corners, storage, thresh_img, flags, &max_quad_buf_size);
PRINTF("Quad count: %d/%d\n", quad_count, (pattern_size.width/2+1)*(pattern_size.height/2+1));
SHOW_QUADS("Old quads", thresh_img, quads, quad_count);
if (processQuads(quads, quad_count, pattern_size, max_quad_buf_size, storage, corners, out_corners, out_corner_count, prev_sqr_size))
found = 1;
}
}
}
PRINTF("Chessboard detection result 1: %d\n", found);
if( found )
found = icvCheckBoardMonotony( out_corners, pattern_size );
PRINTF("Chessboard detection result 2: %d\n", found);
// check that none of the found corners is too close to the image boundary
if( found )
{
const int BORDER = 8;
for( k = 0; k < pattern_size.width*pattern_size.height; k++ )
{
if( out_corners[k].x <= BORDER || out_corners[k].x > img.cols - BORDER ||
out_corners[k].y <= BORDER || out_corners[k].y > img.rows - BORDER )
break;
}
found = k == pattern_size.width*pattern_size.height;
}
PRINTF("Chessboard detection result 3: %d\n", found);
if( found )
{
if ( pattern_size.height % 2 == 0 && pattern_size.width % 2 == 0 )
{
int last_row = (pattern_size.height-1)*pattern_size.width;
double dy0 = out_corners[last_row].y - out_corners[0].y;
if( dy0 < 0 )
{
int n = pattern_size.width*pattern_size.height;
for(int i = 0; i < n/2; i++ )
{
CvPoint2D32f temp;
CV_SWAP(out_corners[i], out_corners[n-i-1], temp);
}
}
}
int wsize = 2;
CvMat old_img(img);
cvFindCornerSubPix( &old_img, out_corners, pattern_size.width*pattern_size.height,
cvSize(wsize, wsize), cvSize(-1,-1),
cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 15, 0.1));
}
}
CV_CATCH_ALL
{
cvFree(&quads);
cvFree(&corners);
CV_RETHROW();
}
cvFree(&quads);
cvFree(&corners);
return found;
}
//
// Checks that each board row and column is pretty much monotonous curve:
// It analyzes each row and each column of the chessboard as following:
// for each corner c lying between end points in the same row/column it checks that
// the point projection to the line segment (a,b) is lying between projections
// of the neighbor corners in the same row/column.
//
// This function has been created as temporary workaround for the bug in current implementation
// of cvFindChessboardCornes that produces absolutely unordered sets of corners.
//
static int
icvCheckBoardMonotony( CvPoint2D32f* corners, CvSize pattern_size )
{
int i, j, k;
for( k = 0; k < 2; k++ )
{
for( i = 0; i < (k == 0 ? pattern_size.height : pattern_size.width); i++ )
{
CvPoint2D32f a = k == 0 ? corners[i*pattern_size.width] : corners[i];
CvPoint2D32f b = k == 0 ? corners[(i+1)*pattern_size.width-1] :
corners[(pattern_size.height-1)*pattern_size.width + i];
float prevt = 0, dx0 = b.x - a.x, dy0 = b.y - a.y;
if( fabs(dx0) + fabs(dy0) < FLT_EPSILON )
return 0;
for( j = 1; j < (k == 0 ? pattern_size.width : pattern_size.height) - 1; j++ )
{
CvPoint2D32f c = k == 0 ? corners[i*pattern_size.width + j] :
corners[j*pattern_size.width + i];
float t = ((c.x - a.x)*dx0 + (c.y - a.y)*dy0)/(dx0*dx0 + dy0*dy0);
if( t < prevt || t > 1 )
return 0;
prevt = t;
}
}
}
return 1;
}
//
// order a group of connected quads
// order of corners:
// 0 is top left
// clockwise from there
// note: "top left" is nominal, depends on initial ordering of starting quad
// but all other quads are ordered consistently
//
// can change the number of quads in the group
// can add quads, so we need to have quad/corner arrays passed in
//
static int
icvOrderFoundConnectedQuads( int quad_count, CvCBQuad **quads,
int *all_count, CvCBQuad **all_quads, CvCBCorner **corners,
CvSize pattern_size, int max_quad_buf_size, CvMemStorage* storage )
{
cv::Ptr<CvMemStorage> temp_storage(cvCreateChildMemStorage( storage ));
CvSeq* stack = cvCreateSeq( 0, sizeof(*stack), sizeof(void*), temp_storage );
// first find an interior quad
CvCBQuad *start = NULL;
for (int i=0; i<quad_count; i++)
{
if (quads[i]->count == 4)
{
start = quads[i];
break;
}
}
if (start == NULL)
return 0; // no 4-connected quad
// start with first one, assign rows/cols
int row_min = 0, col_min = 0, row_max=0, col_max = 0;
std::map<int, int> col_hist;
std::map<int, int> row_hist;
cvSeqPush(stack, &start);
start->row = 0;
start->col = 0;
start->ordered = true;
// Recursively order the quads so that all position numbers (e.g.,
// 0,1,2,3) are in the at the same relative corner (e.g., lower right).
while( stack->total )
{
CvCBQuad* q;
cvSeqPop( stack, &q );
int col = q->col;
int row = q->row;
col_hist[col]++;
row_hist[row]++;
// check min/max
if (row > row_max) row_max = row;
if (row < row_min) row_min = row;
if (col > col_max) col_max = col;
if (col < col_min) col_min = col;
for(int i = 0; i < 4; i++ )
{
CvCBQuad *neighbor = q->neighbors[i];
switch(i) // adjust col, row for this quad
{ // start at top left, go clockwise
case 0:
row--; col--; break;
case 1:
col += 2; break;
case 2:
row += 2; break;
case 3:
col -= 2; break;
}
// just do inside quads
if (neighbor && neighbor->ordered == false && neighbor->count == 4)
{
PRINTF("col: %d row: %d\n", col, row);
icvOrderQuad(neighbor, q->corners[i], (i+2)%4); // set in order
neighbor->ordered = true;
neighbor->row = row;
neighbor->col = col;
cvSeqPush( stack, &neighbor );
}
}
}
for (int i=col_min; i<=col_max; i++)
PRINTF("HIST[%d] = %d\n", i, col_hist[i]);
// analyze inner quad structure
int w = pattern_size.width - 1;
int h = pattern_size.height - 1;
int drow = row_max - row_min + 1;
int dcol = col_max - col_min + 1;
// normalize pattern and found quad indices
if ((w > h && dcol < drow) ||
(w < h && drow < dcol))
{
h = pattern_size.width - 1;
w = pattern_size.height - 1;
}
PRINTF("Size: %dx%d Pattern: %dx%d\n", dcol, drow, w, h);
// check if there are enough inner quads
if (dcol < w || drow < h) // found enough inner quads?
{
PRINTF("Too few inner quad rows/cols\n");
return 0; // no, return
}
#ifdef ENABLE_TRIM_COL_ROW
// too many columns, not very common
if (dcol == w+1) // too many, trim
{
PRINTF("Trimming cols\n");
if (col_hist[col_max] > col_hist[col_min])
{
PRINTF("Trimming left col\n");
quad_count = icvTrimCol(quads,quad_count,col_min,-1);
}
else
{
PRINTF("Trimming right col\n");
quad_count = icvTrimCol(quads,quad_count,col_max,+1);
}
}
// too many rows, not very common
if (drow == h+1) // too many, trim
{
PRINTF("Trimming rows\n");
if (row_hist[row_max] > row_hist[row_min])
{
PRINTF("Trimming top row\n");
quad_count = icvTrimRow(quads,quad_count,row_min,-1);
}
else
{
PRINTF("Trimming bottom row\n");
quad_count = icvTrimRow(quads,quad_count,row_max,+1);
}
}
#endif
// check edges of inner quads
// if there is an outer quad missing, fill it in
// first order all inner quads
int found = 0;
for (int i=0; i<quad_count; i++)
{
if (quads[i]->count == 4)
{ // ok, look at neighbors
int col = quads[i]->col;
int row = quads[i]->row;
for (int j=0; j<4; j++)
{
switch(j) // adjust col, row for this quad
{ // start at top left, go clockwise
case 0:
row--; col--; break;
case 1:
col += 2; break;
case 2:
row += 2; break;
case 3:
col -= 2; break;
}
CvCBQuad *neighbor = quads[i]->neighbors[j];
if (neighbor && !neighbor->ordered && // is it an inner quad?
col <= col_max && col >= col_min &&
row <= row_max && row >= row_min)
{
// if so, set in order
PRINTF("Adding inner: col: %d row: %d\n", col, row);
found++;
icvOrderQuad(neighbor, quads[i]->corners[j], (j+2)%4);
neighbor->ordered = true;
neighbor->row = row;
neighbor->col = col;
}
}
}
}
// if we have found inner quads, add corresponding outer quads,
// which are missing
if (found > 0)
{
PRINTF("Found %d inner quads not connected to outer quads, repairing\n", found);
for (int i=0; i<quad_count && *all_count < max_quad_buf_size; i++)
{
if (quads[i]->count < 4 && quads[i]->ordered)
{
int added = icvAddOuterQuad(quads[i],quads,quad_count,all_quads,*all_count,corners, max_quad_buf_size);
*all_count += added;
quad_count += added;
}
}
if (*all_count >= max_quad_buf_size)
return 0;
}
// final trimming of outer quads
if (dcol == w && drow == h) // found correct inner quads
{
PRINTF("Inner bounds ok, check outer quads\n");
int rcount = quad_count;
for (int i=quad_count-1; i>=0; i--) // eliminate any quad not connected to
// an ordered quad
{
if (quads[i]->ordered == false)
{
bool outer = false;
for (int j=0; j<4; j++) // any neighbors that are ordered?
{
if (quads[i]->neighbors[j] && quads[i]->neighbors[j]->ordered)
outer = true;
}
if (!outer) // not an outer quad, eliminate
{
PRINTF("Removing quad %d\n", i);
icvRemoveQuadFromGroup(quads,rcount,quads[i]);
rcount--;
}
}
}
return rcount;
}
return 0;
}
// add an outer quad
// looks for the neighbor of <quad> that isn't present,
// tries to add it in.
// <quad> is ordered
static int
icvAddOuterQuad( CvCBQuad *quad, CvCBQuad **quads, int quad_count,
CvCBQuad **all_quads, int all_count, CvCBCorner **corners, int max_quad_buf_size )
{
int added = 0;
for (int i=0; i<4 && all_count < max_quad_buf_size; i++) // find no-neighbor corners
{
if (!quad->neighbors[i]) // ok, create and add neighbor
{
int j = (i+2)%4;
PRINTF("Adding quad as neighbor 2\n");
CvCBQuad *q = &(*all_quads)[all_count];
memset( q, 0, sizeof(*q) );
added++;
quads[quad_count] = q;
quad_count++;
// set neighbor and group id
quad->neighbors[i] = q;
quad->count += 1;
q->neighbors[j] = quad;
q->group_idx = quad->group_idx;
q->count = 1; // number of neighbors
q->ordered = false;
q->edge_len = quad->edge_len;
// make corners of new quad
// same as neighbor quad, but offset
CvPoint2D32f pt = quad->corners[i]->pt;
CvCBCorner* corner;
float dx = pt.x - quad->corners[j]->pt.x;
float dy = pt.y - quad->corners[j]->pt.y;
for (int k=0; k<4; k++)
{
corner = &(*corners)[all_count*4+k];
pt = quad->corners[k]->pt;
memset( corner, 0, sizeof(*corner) );
corner->pt = pt;
q->corners[k] = corner;
corner->pt.x += dx;
corner->pt.y += dy;
}
// have to set exact corner
q->corners[j] = quad->corners[i];
// now find other neighbor and add it, if possible
if (quad->neighbors[(i+3)%4] &&
quad->neighbors[(i+3)%4]->ordered &&
quad->neighbors[(i+3)%4]->neighbors[i] &&
quad->neighbors[(i+3)%4]->neighbors[i]->ordered )
{
CvCBQuad *qn = quad->neighbors[(i+3)%4]->neighbors[i];
q->count = 2;
q->neighbors[(j+1)%4] = qn;
qn->neighbors[(i+1)%4] = q;
qn->count += 1;
// have to set exact corner
q->corners[(j+1)%4] = qn->corners[(i+1)%4];
}
all_count++;
}
}
return added;
}
// trimming routines
#ifdef ENABLE_TRIM_COL_ROW
static int
icvTrimCol(CvCBQuad **quads, int count, int col, int dir)
{
int rcount = count;
// find the right quad(s)
for (int i=0; i<count; i++)
{
#ifdef DEBUG_CHESSBOARD
if (quads[i]->ordered)
PRINTF("index: %d cur: %d\n", col, quads[i]->col);
#endif
if (quads[i]->ordered && quads[i]->col == col)