-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathchecker_detector.cpp
1406 lines (1173 loc) · 48.9 KB
/
checker_detector.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 file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
/*
* MIT License
*
* Copyright (c) 2018 Pedro Diamel Marrero Fernández
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "precomp.hpp"
#include "checker_detector.hpp"
#include "graph_cluster.hpp"
#include "bound_min.hpp"
#include "wiener_filter.hpp"
#include "checker_model.hpp"
#include "debug.hpp"
#include <iostream>
namespace cv
{
namespace mcc
{
std::mutex mtx; // mutex for critical section
Ptr<CCheckerDetector> CCheckerDetector::create()
{
return makePtr<CCheckerDetectorImpl>();
}
CCheckerDetectorImpl::
CCheckerDetectorImpl()
{
}
CCheckerDetectorImpl::~CCheckerDetectorImpl()
{
}
bool CCheckerDetectorImpl::
setNet(cv::dnn::Net _net)
{
net = _net;
return !net.empty();
}
bool CCheckerDetectorImpl::
_no_net_process(InputArray image, const TYPECHART chartType, const int nc,
const Ptr<DetectorParameters> ¶ms,
std::vector<cv::Rect> regionsOfInterest)
{
m_checkers.clear();
this->net_used = false;
cv::Mat img = image.getMat();
for (const cv::Rect ®ion : regionsOfInterest)
{
//-------------------------------------------------------------------
// Run the model to find good regions
//-------------------------------------------------------------------
cv::Mat croppedImage = img(region);
#ifdef MCC_DEBUG
std::string pathOut = "./";
#endif
//-------------------------------------------------------------------
// prepare image
//-------------------------------------------------------------------
cv::Mat img_bgr, img_gray;
float asp;
prepareImage(croppedImage, img_gray, img_bgr, asp, params);
#ifdef MCC_DEBUG
showAndSave("prepare_image", img_gray, pathOut);
#endif
//-------------------------------------------------------------------
// thresholding
//-------------------------------------------------------------------
std::vector<cv::Mat> img_bw;
performThreshold(img_gray, img_bw, params);
cv::Mat3f img_rgb_f(img_bgr);
cv::cvtColor(img_rgb_f, img_rgb_f, COLOR_BGR2RGB);
img_rgb_f /= 255;
cv::Mat img_rgb_org, img_ycbcr_org;
std::vector<cv::Mat> rgb_planes(3), ycbcr_planes(3);
// Convert to RGB and YCbCr space
cv::cvtColor(croppedImage, img_rgb_org, COLOR_BGR2RGB);
cv::cvtColor(croppedImage, img_ycbcr_org, COLOR_BGR2YCrCb);
// Get chanels
split(img_rgb_org, rgb_planes);
split(img_ycbcr_org, ycbcr_planes);
parallel_for_(
Range(0, (int)img_bw.size()), [&](const Range &range) {
const int begin = range.start;
const int end = range.end;
for (int i = begin; i < end; i++)
{
#ifdef MCC_DEBUG
showAndSave("threshold_image", img_bw[i], pathOut);
#endif
// find contour
//-------------------------------------------------------------------
ContoursVector contours;
findContours(img_bw[i], contours, params);
if (contours.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat im_contour(img_bgr.size(), CV_8UC1);
im_contour = cv::Scalar(0);
cv::drawContours(im_contour, contours, -1, cv::Scalar(255), 2, LINE_AA);
showAndSave("find_contour", im_contour, pathOut);
#endif
//-------------------------------------------------------------------
// find candidate
//-------------------------------------------------------------------
std::vector<CChart> detectedCharts;
findCandidates(contours, detectedCharts, params);
if (detectedCharts.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat img_chart;
img_bgr.copyTo(img_chart);
for (size_t ind = 0; ind < detectedCharts.size(); ind++)
{
CChartDraw chrtdrw((detectedCharts[ind]), img_chart);
chrtdrw.drawCenter();
chrtdrw.drawContour();
}
showAndSave("find_candidate", img_chart, pathOut);
#endif
//-------------------------------------------------------------------
// clusters analysis
//-------------------------------------------------------------------
std::vector<int> G;
clustersAnalysis(detectedCharts, G, params);
if (G.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat im_gru;
img_bgr.copyTo(im_gru);
RNG rng(0xFFFFFFFF);
int radius = 10, thickness = -1;
std::vector<int> g;
unique(G, g);
size_t Nc = g.size();
std::vector<cv::Scalar> colors(Nc);
for (size_t ind = 0; ind < Nc; ind++)
colors[ind] = randomcolor(rng);
for (size_t ind = 0; ind < detectedCharts.size(); ind++)
cv::circle(im_gru, detectedCharts[ind].center, radius, colors[G[ind]],
thickness);
showAndSave("clusters_analysis", im_gru, pathOut);
#endif
//-------------------------------------------------------------------
// checker color recognize
//-------------------------------------------------------------------
std::vector<std::vector<cv::Point2f>> colorCharts;
checkerRecognize(img_bgr, detectedCharts, G, chartType, colorCharts, params);
if (colorCharts.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat image_box;
img_bgr.copyTo(image_box);
for (size_t ind = 0; ind < colorCharts.size(); ind++)
{
std::vector<cv::Point2f> ibox = colorCharts[ind];
cv::Scalar color_box = CV_RGB(0, 0, 255);
int thickness_box = 2;
cv::line(image_box, ibox[0], ibox[1], color_box, thickness_box, LINE_AA);
cv::line(image_box, ibox[1], ibox[2], color_box, thickness_box, LINE_AA);
cv::line(image_box, ibox[2], ibox[3], color_box, thickness_box, LINE_AA);
cv::line(image_box, ibox[3], ibox[0], color_box, thickness_box, LINE_AA);
//cv::circle(image_box, ibox[0], 10, cv::Scalar(0, 0, 255), 3);
//cv::circle(image_box, ibox[1], 10, cv::Scalar(0, 255, 0), 3);
}
showAndSave("checker_recognition", image_box, pathOut);
#endif
//-------------------------------------------------------------------
// checker color analysis
//-------------------------------------------------------------------
std::vector<Ptr<CChecker>> checkers;
checkerAnalysis(img_rgb_f, chartType, nc, colorCharts, checkers, asp, params,
img_rgb_org, img_ycbcr_org, rgb_planes, ycbcr_planes);
#ifdef MCC_DEBUG
cv::Mat image_checker;
croppedImage.copyTo(image_checker);
for (size_t ck = 0; ck < checkers.size(); ck++)
{
Ptr<CCheckerDraw> cdraw = CCheckerDraw::create((checkers[ck]));
cdraw->draw(image_checker);
}
showAndSave("checker_analysis", image_checker, pathOut);
#endif
for (Ptr<CChecker>& checker : checkers)
{
//std::cout << "===1,get-checkers-box= " << checker->getBox() << std::endl;
std::vector<cv::Point2f> restore_box;
for (cv::Point2f& corner : checker->getBox()) {
corner += static_cast<cv::Point2f>(region.tl());
restore_box.emplace_back(corner);
}
checker->setBox(restore_box);
//std::cout << "===1,get-checkers-box= " << checker->getBox() << std::endl;
mtx.lock(); // push_back is not thread safe
m_checkers.push_back(checker);
mtx.unlock();
}
}
#ifdef MCC_DEBUG
},
1); //Run only one thread in debug mode
#else
});
#endif
}
//remove too close detections
removeTooCloseDetections(params);
m_checkers.resize(min(nc, (int)m_checkers.size()));
return !m_checkers.empty();
}
bool CCheckerDetectorImpl::
process(InputArray image, const TYPECHART chartType,const std::vector<cv::Rect> ®ionsOfInterest,
const int nc /*= 1*/, bool useNet /*=false*/, const Ptr<DetectorParameters> ¶ms)
{
m_checkers.clear();
if (this->net.empty() || !useNet)
{
return _no_net_process(image, chartType, nc, params, regionsOfInterest);
}
this->net_used = true;
cv::Mat img = image.getMat();
for (const cv::Rect ®ion : regionsOfInterest)
{
cv::Mat croppedImage = img(region);
cv::Mat img_rgb_org, img_ycbcr_org;
// Convert to RGB and YCbCr space
cv::cvtColor(croppedImage, img_rgb_org, COLOR_BGR2RGB);
cv::cvtColor(croppedImage, img_ycbcr_org, COLOR_BGR2YCrCb);
//-------------------------------------------------------------------
// Run the model to find good regions
//-------------------------------------------------------------------
int rows = croppedImage.size[0];
int cols = croppedImage.size[1];
net.setInput(cv::dnn::blobFromImage(croppedImage, 1.0, cv::Size(), cv::Scalar(), true));
cv::Mat output = net.forward();
Mat detectionMat(output.size[2], output.size[3], CV_32F, output.ptr<float>());
for (int i = 0; i < detectionMat.rows; i++)
{
float confidence = detectionMat.at<float>(i, 2);
if (confidence > params->confidenceThreshold)
{
float xTopLeft = max(0.0f, detectionMat.at<float>(i, 3) * cols - params->borderWidth);
float yTopLeft = max(0.0f, detectionMat.at<float>(i, 4) * rows - params->borderWidth);
float xBottomRight = min((float)cols - 1, detectionMat.at<float>(i, 5) * cols + params->borderWidth);
float yBottomRight = min((float)rows - 1, detectionMat.at<float>(i, 6) * rows + params->borderWidth);
cv::Point2f topLeft = {xTopLeft, yTopLeft};
cv::Point2f bottomRight = {xBottomRight, yBottomRight};
cv::Rect innerRegion(topLeft, bottomRight);
cv::Mat innerCroppedImage = croppedImage(innerRegion);
#ifdef MCC_DEBUG
std::string pathOut = "./";
#endif
//-------------------------------------------------------------------
// prepare image
//-------------------------------------------------------------------
cv::Mat img_bgr, img_gray;
float asp;
prepareImage(innerCroppedImage, img_gray, img_bgr, asp, params);
//-------------------------------------------------------------------
// thresholding
//-------------------------------------------------------------------
std::vector<cv::Mat> img_bw;
performThreshold(img_gray, img_bw, params);
cv::Mat3f img_rgb_f(img_bgr);
cv::cvtColor(img_rgb_f, img_rgb_f, COLOR_BGR2RGB);
img_rgb_f /= 255;
parallel_for_(
Range(0, (int)img_bw.size()), [&](const Range &range) {
const int begin = range.start;
const int end = range.end;
for (int ind = begin; ind < end; ind++)
{
#ifdef MCC_DEBUG
showAndSave("threshold_image", img_bw[ind], pathOut);
#endif
//------------------------------------------------------------------
// find contour
//-------------------------------------------------------------------
ContoursVector contours;
findContours(img_bw[ind], contours, params);
if (contours.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat im_contour(img_bgr.size(), CV_8UC1);
im_contour = cv::Scalar(0);
cv::drawContours(im_contour, contours, -1, cv::Scalar(255), 2, LINE_AA);
showAndSave("find_contour", im_contour, pathOut);
#endif
//-------------------------------------------------------------------
// find candidate
//-------------------------------------------------------------------
std::vector<CChart> detectedCharts;
findCandidates(contours, detectedCharts, params);
if (detectedCharts.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat img_chart;
img_bgr.copyTo(img_chart);
for (size_t index = 0; index < detectedCharts.size(); index++)
{
CChartDraw chrtdrw((detectedCharts[index]), img_chart);
chrtdrw.drawCenter();
chrtdrw.drawContour();
}
showAndSave("find_candidate", img_chart, pathOut);
#endif
//-------------------------------------------------------------------
// clusters analysis
//-------------------------------------------------------------------
std::vector<int> G;
clustersAnalysis(detectedCharts, G, params);
if (G.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat im_gru;
img_bgr.copyTo(im_gru);
RNG rng(0xFFFFFFFF);
int radius = 10, thickness = -1;
std::vector<int> g;
unique(G, g);
size_t Nc = g.size();
std::vector<cv::Scalar> colors(Nc);
for (size_t index = 0; index < Nc; index++)
colors[index] = randomcolor(rng);
for (size_t index = 0; index < detectedCharts.size(); index++)
cv::circle(im_gru, detectedCharts[index].center, radius, colors[G[index]],
thickness);
showAndSave("clusters_analysis", im_gru, pathOut);
#endif
//-------------------------------------------------------------------
// checker color recognize
//-------------------------------------------------------------------
std::vector<std::vector<cv::Point2f>> colorCharts;
checkerRecognize(img_bgr, detectedCharts, G, chartType, colorCharts, params);
if (colorCharts.empty())
continue;
#ifdef MCC_DEBUG
cv::Mat image_box;
img_bgr.copyTo(image_box);
for (size_t index = 0; index < colorCharts.size(); index++)
{
std::vector<cv::Point2f> ibox = colorCharts[index];
cv::Scalar color_box = CV_RGB(0, 0, 255);
int thickness_box = 2;
cv::line(image_box, ibox[0], ibox[1], color_box, thickness_box, LINE_AA);
cv::line(image_box, ibox[1], ibox[2], color_box, thickness_box, LINE_AA);
cv::line(image_box, ibox[2], ibox[3], color_box, thickness_box, LINE_AA);
cv::line(image_box, ibox[3], ibox[0], color_box, thickness_box, LINE_AA);
//cv::circle(image_box, ibox[0], 10, cv::Scalar(0, 0, 255), 3);
//cv::circle(image_box, ibox[1], 10, cv::Scalar(0, 255, 0), 3);
}
showAndSave("checker_recognition", image_box, pathOut);
#endif
cv::Mat img_rgb_org_roi = img_rgb_org(innerRegion);
cv::Mat img_ycbcr_org_roi = img_ycbcr_org(innerRegion);
// Get chanels
std::vector<cv::Mat> rgb_planes(3), ycbcr_planes(3);
split(img_rgb_org_roi, rgb_planes);
split(img_ycbcr_org_roi, ycbcr_planes);
//-------------------------------------------------------------------
// checker color analysis
//-------------------------------------------------------------------
std::vector<Ptr<CChecker>> checkers;
checkerAnalysis(img_rgb_f, chartType, nc, colorCharts, checkers, asp, params,
img_rgb_org_roi, img_ycbcr_org_roi, rgb_planes, ycbcr_planes);
#ifdef MCC_DEBUG
cv::Mat image_checker;
innerCroppedImage.copyTo(image_checker);
for (size_t ck = 0; ck < checkers.size(); ck++)
{
Ptr<CCheckerDraw> cdraw = CCheckerDraw::create((checkers[ck]));
cdraw->draw(image_checker);
}
showAndSave("checker_analysis", image_checker, pathOut);
#endif
for (Ptr<CChecker>& checker : checkers)
{
//std::cout<<"===1,get-checkers-box= "<<checker->getBox()<<std::endl;
std::vector<cv::Point2f> restore_box;
for (cv::Point2f& corner : checker->getBox()) {
corner += static_cast<cv::Point2f>(region.tl() + innerRegion.tl());
restore_box.emplace_back(corner);
}
checker->setBox(restore_box);
//std::cout<<"===2,get-checkers-box= "<<checker->getBox()<<std::endl;
mtx.lock(); // push_back is not thread safe
m_checkers.push_back(checker);
mtx.unlock();
}
}
#ifdef MCC_DEBUG
},
1); //Run only one thread in debug mode
#else
});
#endif
}
}
}
// As a failsafe try the classical method
if (m_checkers.empty())
{
return _no_net_process(image, chartType, nc, params, regionsOfInterest);
}
//remove too close detections
removeTooCloseDetections(params);
m_checkers.resize(min(nc, (int)m_checkers.size()));
return !m_checkers.empty();
}
//Overload for the above function
bool CCheckerDetectorImpl::
process(InputArray image, const TYPECHART chartType,
const int nc /*= 1*/, bool useNet /*=false*/, const Ptr<DetectorParameters> ¶ms)
{
return process(image, chartType, std::vector<cv::Rect>(1, Rect(0, 0, image.cols(), image.rows())),
nc,useNet, params);
}
void CCheckerDetectorImpl::
prepareImage(InputArray bgr, OutputArray grayOut,
OutputArray bgrOut, float &aspOut,
const Ptr<DetectorParameters> ¶ms) const
{
int min_size;
cv::Size size = bgr.size();
aspOut = 1;
bgr.copyTo(bgrOut);
// Resize image
min_size = std::min(size.width, size.height);
if (params->minImageSize > min_size)
{
aspOut = (float)params->minImageSize / min_size;
cv::resize(bgr, bgrOut, cv::Size(int(size.width * aspOut), int(size.height * aspOut)));
}
// Convert to grayscale
cv::cvtColor(bgrOut, grayOut, COLOR_BGR2GRAY);
// PDiamel: wiener adaptative methods to minimize the noise effets
// by illumination
CWienerFilter filter;
filter.wiener2(grayOut, grayOut, 5, 5);
//JLeandro: perform morphological open on the equalized image
//to minimize the noise effects by CLAHE and to even intensities
//inside the MCC patches (regions)
cv::Mat strelbox = cv::getStructuringElement(cv::MORPH_RECT, Size(5, 5));
cv::morphologyEx(grayOut, grayOut, MORPH_OPEN, strelbox);
}
void CCheckerDetectorImpl::
performThreshold(InputArray grayscaleImg,
OutputArrayOfArrays thresholdImgs,
const Ptr<DetectorParameters> ¶ms) const
{
// number of window sizes (scales) to apply adaptive thresholding
int nScales = (params->adaptiveThreshWinSizeMax - params->adaptiveThreshWinSizeMin) / params->adaptiveThreshWinSizeStep + 1;
thresholdImgs.create(nScales, 1, CV_8U);
std::vector<cv::Mat> _thresholdImgs;
for (int i = 0; i < nScales; i++)
{
int currScale = params->adaptiveThreshWinSizeMin + i * params->adaptiveThreshWinSizeStep;
cv::Mat tempThresholdImg;
cv::adaptiveThreshold(grayscaleImg, tempThresholdImg, 255, cv::ADAPTIVE_THRESH_MEAN_C,
cv::THRESH_BINARY_INV, currScale, params->adaptiveThreshConstant);
_thresholdImgs.push_back(tempThresholdImg);
}
thresholdImgs.assign(_thresholdImgs);
}
void CCheckerDetectorImpl::
findContours(
InputArray srcImg,
ContoursVector &contours,
const Ptr<DetectorParameters> ¶ms) const
{
// contour detected
// [Suzuki85] Suzuki, S. and Abe, K., Topological Structural Analysis of Digitized
// Binary Images by Border Following. CVGIP 30 1, pp 32-46 (1985)
ContoursVector allContours;
cv::findContours(srcImg, allContours, RETR_LIST, CHAIN_APPROX_NONE);
//select contours
contours.clear();
const long long int srcImgArea = srcImg.rows() * srcImg.cols();
for (size_t i = 0; i < allContours.size(); i++)
{
PointsVector contour;
contour = allContours[i];
int contourSize = (int)contour.size();
if (contourSize <= params->minContourPointsAllowed)
continue;
double area = cv::contourArea(contour);
// double perm = cv::arcLength(contour, true);
if (this->net_used && area / srcImgArea < params->minContoursAreaRate)
continue;
if (!this->net_used && area < params->minContoursArea)
continue;
// Circularity factor condition
// KORDECKI, A., & PALUS, H. (2014). Automatic detection of colour charts in images.
// Przegl?d Elektrotechniczny, 90(9), 197-202.
// 0.65 < \frac{4*pi*A}{P^2} < 0.97
// double Cf = 4 * CV_PI * area / (perm * perm);
// if (Cf < 0.5 || Cf > 0.97) continue;
// Soliditys
// This measure is proposed in this work.
PointsVector hull;
cv::convexHull(contour, hull);
double area_hull = cv::contourArea(hull);
double S = area / area_hull;
if (S < params->minContourSolidity)
continue;
// Texture analysis
// ...
contours.push_back(allContours[i]);
}
}
void CCheckerDetectorImpl::
findCandidates(
const ContoursVector &contours,
std::vector<CChart> &detectedCharts,
const Ptr<DetectorParameters> ¶ms)
{
std::vector<cv::Point> approxCurve;
std::vector<CChart> possibleCharts;
// For each contour, analyze if it is a parallelepiped likely to be the chart
for (size_t i = 0; i < contours.size(); i++)
{
// Approximate to a polygon
// It uses the Douglas-Peucker algorithm
// http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
double eps = contours[i].size() * params->findCandidatesApproxPolyDPEpsMultiplier;
cv::approxPolyDP(contours[i], approxCurve, eps, true);
// We interested only in polygons that contains only four points
if (approxCurve.size() != 4)
continue;
// And they have to be convex
if (!cv::isContourConvex(approxCurve))
continue;
// Ensure that the distance between consecutive points is large enough
float minDist = INFINITY;
for (size_t j = 0; j < 4; j++)
{
cv::Point side = approxCurve[j] - approxCurve[(j + 1) % 4];
float squaredSideLength = (float)side.dot(side);
minDist = std::min(minDist, squaredSideLength);
}
// Check that distance is not very small
if (minDist < params->minContourLengthAllowed)
continue;
// All tests are passed. Save chart candidate:
CChart chart;
std::vector<cv::Point2f> corners(4);
for (int j = 0; j < 4; j++)
corners[j] = cv::Point2f((float)approxCurve[j].x, (float)approxCurve[j].y);
chart.setCorners(corners);
possibleCharts.push_back(chart);
}
// Remove these elements which corners are too close to each other.
// Eliminate overlaps!!!
// First detect candidates for removal:
std::vector<std::pair<int, int>> tooNearCandidates;
for (int i = 0; i < (int)possibleCharts.size(); i++)
{
const CChart &m1 = possibleCharts[i];
//calculate the average distance of each corner to the nearest corner of the other chart candidate
for (int j = i + 1; j < (int)possibleCharts.size(); j++)
{
const CChart &m2 = possibleCharts[j];
float distSquared = 0;
for (int c = 0; c < 4; c++)
{
cv::Point v = m1.corners[c] - m2.corners[c];
distSquared += v.dot(v);
}
distSquared /= 4;
if (distSquared < params->minInterContourDistance)
{
tooNearCandidates.push_back(std::pair<int, int>(i, j));
}
}
}
// Mark for removal the element of the pair with smaller perimeter
std::vector<bool> removalMask(possibleCharts.size(), false);
for (size_t i = 0; i < tooNearCandidates.size(); i++)
{
float p1 = perimeter(possibleCharts[tooNearCandidates[i].first].corners);
float p2 = perimeter(possibleCharts[tooNearCandidates[i].second].corners);
size_t removalIndex;
if (p1 > p2)
removalIndex = tooNearCandidates[i].second;
else
removalIndex = tooNearCandidates[i].first;
removalMask[removalIndex] = true;
}
// Return candidates
detectedCharts.clear();
for (size_t i = 0; i < possibleCharts.size(); i++)
{
if (removalMask[i])
continue;
detectedCharts.push_back(possibleCharts[i]);
}
}
void CCheckerDetectorImpl::
clustersAnalysis(
const std::vector<CChart> &detectedCharts,
std::vector<int> &groups,
const Ptr<DetectorParameters> ¶ms)
{
size_t N = detectedCharts.size();
std::vector<cv::Point> X(N);
std::vector<double> B0(N), W(N);
std::vector<int> G;
CChart chart;
double b0;
for (size_t i = 0; i < N; i++)
{
chart = detectedCharts[i];
b0 = chart.large_side * params->B0factor;
X[i] = chart.center;
W[i] = chart.area;
B0[i] = b0;
}
CB0cluster bocluster;
bocluster.setVertex(X);
bocluster.setWeight(W);
bocluster.setB0(B0);
bocluster.group();
bocluster.getGroup(G);
groups = G;
}
void CCheckerDetectorImpl::
checkerRecognize(
InputArray img,
const std::vector<CChart> &detectedCharts,
const std::vector<int> &G,
const TYPECHART chartType,
std::vector<std::vector<cv::Point2f>> &colorChartsOut,
const Ptr<DetectorParameters> ¶ms)
{
std::vector<int> gU;
unique(G, gU);
size_t Nc = gU.size(); //numero de grupos
size_t Ncc = detectedCharts.size(); //numero de charts
std::vector<std::vector<cv::Point2f>> colorCharts;
for (size_t g = 0; g < Nc; g++)
{
///-------------------------------------------------
/// selecionar grupo i-esimo
std::vector<CChart> chartSub;
for (size_t i = 0; i < Ncc; i++)
if (G[i] == (int)g)
chartSub.push_back(detectedCharts[i]);
size_t Nsc = chartSub.size();
if (Nsc < params->minGroupSize)
continue;
///-------------------------------------------------
/// min box estimation
CBoundMin bm;
std::vector<cv::Point2f> points;
bm.setCharts(chartSub);
bm.calculate();
bm.getCorners(points);
// boundary condition
if (points.size() == 0)
continue;
// sort the points in anti-clockwise order
polyanticlockwise(points);
///-------------------------------------------------
/// box projective transformation
// get physical char box model
std::vector<cv::Point2f> chartPhy;
get_subbox_chart_physical(points, chartPhy);
// Find the perspective transformation that brings current chart to rectangular form
Matx33f ccT = cv::getPerspectiveTransform(points, chartPhy);
// transformer
std::vector<cv::Point2f> c(Nsc), ct;
std::vector<cv::Point2f> ch(4 * Nsc), cht;
for (size_t i = 0; i < Nsc; i++)
{
CChart cc = chartSub[i];
for (size_t j = 0; j < 4; j++)
ch[i * 4 + j] = cc.corners[j];
c[i] = chartSub[i].center;
}
transform_points_forward(ccT, c, ct);
transform_points_forward(ccT, ch, cht);
float wchart = 0, hchart = 0;
std::vector<float> cx(Nsc), cy(Nsc);
for (size_t i = 0, k = 0; i < Nsc; i++)
{
k = i * 4;
cv::Point2f v1 = cht[k + 1] - cht[k + 0];
cv::Point2f v2 = cht[k + 3] - cht[k + 0];
wchart += (float)norm(v1);
hchart += (float)norm(v2);
cx[i] = ct[i].x;
cy[i] = ct[i].y;
}
wchart /= Nsc;
hchart /= Nsc;
///-------------------------------------------------
/// centers and color estimate
float tolx = wchart / 2, toly = hchart / 2;
std::vector<float> cxr, cyr;
reduce_array(cx, cxr, tolx);
reduce_array(cy, cyr, toly);
if (cxr.size() == 1 || cyr.size() == 1) //no information can be extracted if \
//only one row or columns in present
continue;
// color and center rectificate
cv::Size2i colorSize = cv::Size2i((int)cxr.size(), (int)cyr.size());
cv::Mat colorMat(colorSize, CV_32FC3);
std::vector<cv::Point2f> cte(colorSize.area());
int k = 0;
for (int i = 0; i < colorSize.height; i++)
{
for (int j = 0; j < colorSize.width; j++)
{
cv::Point2f vc = cv::Point2f(cxr[j], cyr[i]);
cte[k] = vc;
// recovery color
cv::Point2f cti;
cv::Matx31f p, xt;
p(0, 0) = vc.x;
p(1, 0) = vc.y;
p(2, 0) = 1;
xt = ccT.inv() * p;
cti.x = xt(0, 0) / xt(2, 0);
cti.y = xt(1, 0) / xt(2, 0);
// color
int x, y;
x = (int)cti.x;
y = (int)cti.y;
Vec3f &srgb = colorMat.at<Vec3f>(i, j);
Vec3b rgb;
if (0 <= y && y < img.rows() && 0 <= x && x < img.cols())
rgb = img.getMat().at<Vec3b>(y, x);
srgb[0] = (float)rgb[0] / 255;
srgb[1] = (float)rgb[1] / 255;
srgb[2] = (float)rgb[2] / 255;
k++;
}
}
CChartModel::SUBCCMModel scm;
scm.centers = cte;
scm.color_size = colorSize;
colorMat = colorMat.t();
scm.sub_chart = colorMat.reshape(3, colorSize.area());
///-------------------------------------------------
// color chart model
CChartModel cccm(chartType);
int iTheta; // rotation angle of chart
int offset; // offset
float error; // min error
if (!cccm.evaluate(scm, offset, iTheta, error))
continue;
if (iTheta >= 4)
cccm.flip();
for (int i = 0; i < iTheta % 4; i++)
cccm.rotate90();
///-------------------------------------------------
/// calculate coordanate
cv::Size2i dim = cccm.size;
std::vector<cv::Point2f> center = cccm.center;
std::vector<cv::Point2f> box = cccm.box;
int cols = dim.height - colorSize.width + 1;
int x = (offset) / cols;
int y = (offset) % cols;
// seleccionar sub grid centers of model
std::vector<cv::Point2f> ctss(colorSize.area());
cv::Point2f point_ac = cv::Point2f(0, 0);
int p = 0;
for (int i = x; i < (x + colorSize.height); i++)
{
for (int j = y; j < (y + colorSize.width); j++)
{
int iter = i * dim.height + j;
ctss[p] = center[iter];
point_ac += ctss[p];
p++;
}
}
// is colineal point
if (point_ac.x == ctss[0].x * p || point_ac.y == ctss[0].y * p)
continue;
// Find the perspective transformation
cv::Matx33f ccTe = cv::findHomography(ctss, cte);
std::vector<cv::Point2f> tbox, ibox;
transform_points_forward(ccTe, box, tbox);
transform_points_inverse(ccT, tbox, ibox);
// sort the points in anti-clockwise order
if (iTheta < 4)
mcc::polyanticlockwise(ibox);
else
mcc::polyclockwise(ibox);
// circshift(ibox, 4 - iTheta);
colorCharts.push_back(ibox);
}
// return
colorChartsOut = colorCharts;
}
void CCheckerDetectorImpl::
checkerAnalysis(
InputArray img_f,
const TYPECHART chartType,
const unsigned int nc,
const std::vector<std::vector<cv::Point2f>> &colorCharts,
std::vector<Ptr<CChecker>> &checkers,
float asp,
const Ptr<DetectorParameters> ¶ms,
const cv::Mat &img_rgb_org,
const cv::Mat &img_ycbcr_org,
std::vector<cv::Mat> &rgb_planes,
std::vector<cv::Mat> &ycbcr_planes)
{
size_t N;
std::vector<cv::Point2f> ibox;
// color chart classic model