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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
|
//#include <iostream>
//#include <vector>
//#include <opencv2/core.hpp>
//#include <opencv2/imgproc.hpp>
//#include <opencv2/highgui.hpp>
//#include <opencv2/features2d.hpp>
//#include <opencv2/calib3d.hpp>
//#include <opencv2/objdetect.hpp>
//#include <opencv2/xfeatures2d.hpp>
//#include <opencv2/stitching.hpp>
//
//#include "RobustMatcher.h"
//#include "TargetMatcher.h"
//
//using namespace std;
//using namespace cv;
//
//int main()
//{
// ////1.计算图像对的基础矩阵
// //Mat image1 = imread("./images/church01.jpg", 0);
// //Mat image2 = imread("./images/church03.jpg", 0);
// //if (!image1.data || !image2.data)
// // return 0;
//
// //// Display the images
// //cv::namedWindow("Right Image");
// //cv::imshow("Right Image", image1);
// //cv::namedWindow("Left Image");
// //cv::imshow("Left Image", image2);
//
// ////定义关键点容器和描述子、
// //vector<KeyPoint> keypoints1;
// //vector<KeyPoint> keypoints2;
// //Mat descriptors1, descriptors2;
// ////构建SIFT特征检测器
// //Ptr<Feature2D> ptrFeature2D = xfeatures2d::SIFT::create(74);
//
// //ptrFeature2D->detectAndCompute(image1, noArray(), keypoints1, descriptors1);
// //ptrFeature2D->detectAndCompute(image2, noArray(), keypoints2, descriptors2);
//
// //std::cout << "Number of SIFT points (1): " << keypoints1.size() << std::endl;
// //std::cout << "Number of SIFT points (2): " << keypoints2.size() << std::endl;
//
// ////画关键点
// //cv::Mat imageKP;
// //cv::drawKeypoints(image1, keypoints1, imageKP, cv::Scalar(255, 255, 255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// //cv::namedWindow("Right SIFT Features");
// //cv::imshow("Right SIFT Features", imageKP);
// //cv::drawKeypoints(image2, keypoints2, imageKP, cv::Scalar(255, 255, 255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// //cv::namedWindow("Left SIFT Features");
// //cv::imshow("Left SIFT Features", imageKP);
//
// ////构建匹配类的实例
// //BFMatcher matcher(NORM_L2, true);
// ////匹配描述子
// //vector<DMatch> matches;
// //matcher.match(descriptors1, descriptors2, matches);
// //std::cout << "Number of matched points: " << matches.size() << std::endl;
// ////手动的选择一些匹配的描述子
// //vector<DMatch> selMatches;
// //// make sure to double-check if the selected matches are valid
// //selMatches.push_back(matches[2]);
// //selMatches.push_back(matches[5]);
// //selMatches.push_back(matches[16]);
// //selMatches.push_back(matches[19]);
// //selMatches.push_back(matches[14]);
// //selMatches.push_back(matches[34]);
// //selMatches.push_back(matches[29]);
//
// ////画出选择的描述子
// //cv::Mat imageMatches;
// //cv::drawMatches(image1, keypoints1, // 1st image and its keypoints
// // image2, keypoints2, // 2nd image and its keypoints
// // selMatches, // the selected matches
// // imageMatches, // the image produced
// // cv::Scalar(255, 255, 255),
// // cv::Scalar(255, 255, 255),
// // std::vector<char>(),
// // 2
// //); // color of the lines
// //cv::namedWindow("Matches");
// //cv::imshow("Matches", imageMatches);
// ////将一维关键点转变为二维的点
// //vector<int> pointIndexes1;
// //vector<int> pointIndexes2;
// //for (vector<DMatch>::const_iterator it = selMatches.begin(); it != selMatches.end(); ++it)
// //{
// // pointIndexes1.push_back(it->queryIdx);
// // pointIndexes2.push_back(it->trainIdx);
// //}
// ////为了在findFundamentalMat中使用,需要先把这些关键点转化为Point2f类型
// //vector<Point2f> selPoints1, selPoints2;
// //KeyPoint::convert(keypoints1, selPoints1, pointIndexes1);
// //KeyPoint::convert(keypoints2, selPoints2, pointIndexes2);
// ////通过画点来检查
// //vector<Point2f> ::const_iterator it = selPoints1.begin();
// //while (it != selPoints1.end())
// //{
// // //在每个角点位置画圆
// // circle(image1, *it, 3, Scalar(255, 255, 255), 2);
// // ++it;
// //}
// //it = selPoints2.begin();
// //while (it != selPoints2.end()) {
//
// // // draw a circle at each corner location
// // cv::circle(image2, *it, 3, cv::Scalar(255, 255, 255), 2);
// // ++it;
// //}
// ////用7对匹配项计算基础矩阵
// //Mat fundamental = findFundamentalMat(
// // selPoints1, //第一幅图像的7个点
// // selPoints2, //第二幅图像的7个点
// // FM_7POINT); //7个点的方法
// //cout << "F-Matrix size= " << fundamental.rows << "," << fundamental.cols << endl;
// //Mat fund(fundamental, cv::Rect(0, 0, 3, 3));
// ////在右侧图像上画出对极线的左侧点
// //vector<Vec3f> lines1;
// //computeCorrespondEpilines(selPoints1, //图像点
// // 1, //在第一副图像中(也可在第二幅图像中)
// // fund, //基础矩阵
// // lines1); //对极线的向量
// //std::cout << "size of F matrix:" << fund.rows << "x" << fund.cols << std::endl;
// ////遍历全部对极线
// //for (std::vector<cv::Vec3f>::const_iterator it = lines1.begin();
// // it != lines1.end(); ++it) {
//
// // // 画出第一列和最后一列之间的线条
// // cv::line(image2, cv::Point(0, -(*it)[2] / (*it)[1]),
// // cv::Point(image2.cols, -((*it)[2] + (*it)[0] * image2.cols) / (*it)[1]),
// // cv::Scalar(255, 255, 255));
// //}
//
// //// draw the left points corresponding epipolar lines in left image
// //std::vector<cv::Vec3f> lines2;
// //cv::computeCorrespondEpilines(cv::Mat(selPoints2), 2, fund, lines2);
// //for (std::vector<cv::Vec3f>::const_iterator it = lines2.begin();
// // it != lines2.end(); ++it) {
//
// // // draw the epipolar line between first and last column
// // cv::line(image1, cv::Point(0, -(*it)[2] / (*it)[1]),
// // cv::Point(image1.cols, -((*it)[2] + (*it)[0] * image1.cols) / (*it)[1]),
// // cv::Scalar(255, 255, 255));
// //}
//
// //// combine both images
// //cv::Mat both(image1.rows, image1.cols + image2.cols, CV_8U);
// //image1.copyTo(both.colRange(0, image1.cols));
// //image2.copyTo(both.colRange(image1.cols, image1.cols + image2.cols));
//
// //// Display the images with points and epipolar lines
// //cv::namedWindow("Epilines");
// //cv::imshow("Epilines", both);
// ///*
// //// Convert keypoints into Point2f
// //std::vector<cv::Point2f> points1, points2, newPoints1, newPoints2;
// //cv::KeyPoint::convert(keypoints1, points1);
// //cv::KeyPoint::convert(keypoints2, points2);
// //cv::correctMatches(fund, points1, points2, newPoints1, newPoints2);
// //cv::KeyPoint::convert(newPoints1, keypoints1);
// //cv::KeyPoint::convert(newPoints2, keypoints2);
//
// //cv::drawMatches(image1, keypoints1, // 1st image and its keypoints
// //image2, keypoints2, // 2nd image and its keypoints
// //matches, // the matches
// //imageMatches, // the image produced
// //cv::Scalar(255, 255, 255),
// //cv::Scalar(255, 255, 255),
// //std::vector<char>(),
// //2
// //); // color of the lines
// //cv::namedWindow("Corrected matches");
// //cv::imshow("Corrected matches", imageMatches);
// //*/
//
//
//
// //2.用RANSAC算法匹配图像
//
// // Read input images
// // cv::Mat image1 = cv::imread("./images/church01.jpg", 0);
// // cv::Mat image2 = cv::imread("./images/church03.jpg", 0);
//
// // if (!image1.data || !image2.data)
// // return 0;
//
// // // Display the images
// // cv::namedWindow("Right Image");
// // cv::imshow("Right Image", image1);
// // cv::namedWindow("Left Image");
// //cv::imshow("Left Image", image2);
//
// ////准备匹配器(用默认参数)
// ////SIFT检测器和描述子
// //RobustMatcher rmatcher(xfeatures2d::SIFT::create(250));
// ////匹配两幅图像
// //vector<DMatch> matches;
//
// //vector<KeyPoint> keypoints1, keypoints2;
// //Mat fundamental = rmatcher.match(image1, image2, matches, keypoints1, keypoints2);
//
// //Mat imageMatches;
// //drawMatches(image1, keypoints1, image2, keypoints2, matches, imageMatches,
// // Scalar(255, 255, 255), Scalar(255, 255, 255), vector<char>(), 2);
//
// //imshow("Matches", imageMatches);
//
// //// Convert keypoints into Point2f
// //std::vector<cv::Point2f> points1, points2;
//
// //for (std::vector<cv::DMatch>::const_iterator it = matches.begin();
// // it != matches.end(); ++it) {
//
// // // Get the position of left keypoints
// // float x = keypoints1[it->queryIdx].pt.x;
// // float y = keypoints1[it->queryIdx].pt.y;
// // points1.push_back(keypoints1[it->queryIdx].pt);
// // cv::circle(image1, cv::Point(x, y), 3, cv::Scalar(255, 255, 255), 3);
// // // Get the position of right keypoints
// // x = keypoints2[it->trainIdx].pt.x;
// // y = keypoints2[it->trainIdx].pt.y;
// // cv::circle(image2, cv::Point(x, y), 3, cv::Scalar(255, 255, 255), 3);
// // points2.push_back(keypoints2[it->trainIdx].pt);
// //}
//
// //// Draw the epipolar lines
// //std::vector<cv::Vec3f> lines1;
// //cv::computeCorrespondEpilines(points1, 1, fundamental, lines1);
//
// //for (std::vector<cv::Vec3f>::const_iterator it = lines1.begin();
// // it != lines1.end(); ++it) {
//
// // cv::line(image2, cv::Point(0, -(*it)[2] / (*it)[1]),
// // cv::Point(image2.cols, -((*it)[2] + (*it)[0] * image2.cols) / (*it)[1]),
// // cv::Scalar(255, 255, 255));
// //}
//
// //std::vector<cv::Vec3f> lines2;
// //cv::computeCorrespondEpilines(points2, 2, fundamental, lines2);
//
// //for (std::vector<cv::Vec3f>::const_iterator it = lines2.begin();
// // it != lines2.end(); ++it) {
//
// // cv::line(image1, cv::Point(0, -(*it)[2] / (*it)[1]),
// // cv::Point(image1.cols, -((*it)[2] + (*it)[0] * image1.cols) / (*it)[1]),
// // cv::Scalar(255, 255, 255));
// //}
//
// //// Display the images with epipolar lines
// //cv::namedWindow("Right Image Epilines (RANSAC)");
// //cv::imshow("Right Image Epilines (RANSAC)", image1);
// //cv::namedWindow("Left Image Epilines (RANSAC)");
// //cv::imshow("Left Image Epilines (RANSAC)", image2);
//
//
//
// ////3.计算两幅图像之间的单应矩阵----找到对应的点和拼接两幅图像
// //// Read input images
// // cv::Mat image1 = cv::imread("./images/parliament1.jpg", 0);
// // cv::Mat image2 = cv::imread("./images/parliament2.jpg", 0);
// // if (!image1.data || !image2.data)
// // return 0;
//
// // // Display the images
// // cv::namedWindow("Image 1");
// // cv::imshow("Image 1", image1);
// // cv::namedWindow("Image 2");
// // cv::imshow("Image 2", image2);
//
// ////构建关键点容器和描述子
// //vector<KeyPoint> keypoints1;
// //vector<KeyPoint> keypoints2;
// //Mat descriptors1, descriptors2;
// // //构建SIFT特征检测器
// //Ptr<Feature2D> ptrFeature2D = xfeatures2d::SIFT::create(74);
// //ptrFeature2D->detectAndCompute(image1, noArray() ,keypoints1, descriptors1);
// //ptrFeature2D->detectAndCompute(image2, noArray(), keypoints2, descriptors2);
//
// //cout << " Number of feature points (1):" << keypoints1.size() << endl;
// //cout << " Number of feature points (2):" << keypoints2.size() << endl;
//
// //BFMatcher matcher(NORM_L2, true);
// //vector<DMatch> matches;
// //matcher.match(descriptors1, descriptors2, matches);
//
// //Mat imageMatches;
// //drawMatches(image1, keypoints1, image2, keypoints2, matches, imageMatches,
// // Scalar(255, 255, 255), Scalar(255, 255, 255), vector<char>(), 2);
// //imshow("Matches (pure rotation case)", imageMatches);
//
// ////接下来使用findHomography函数实现,和findFundamentalMat函数相似
// ////我们要将关键点转变为Point2f
// //vector<Point2f> points1, points2;
// //for (vector<DMatch>::const_iterator it = matches.begin(); it != matches.end(); ++it)
// //{
// // //获得左边关键点的位置
// // float x = keypoints1[it->queryIdx].pt.x;
// // float y = keypoints1[it->queryIdx].pt.y;
// // points1.push_back(Point2f(x, y));
// // //获得右边关键点的位置
// // x = keypoints2[it->trainIdx].pt.x;
// // y = keypoints2[it->trainIdx].pt.y;
// // points2.push_back(Point2f(x, y));
// //}
//
// //cout << points1.size() << " " << points2.size() << endl;
// ////找到第一幅图像和第二幅图像之间的单应矩阵
// //vector<char> inliers;
// //Mat homography = findHomography(
// // points1, points2, //对应的点
// // inliers, //输出的局部匹配项
// // RANSAC, //RANSAC方法
// // 1.); //到重复投影点最大的距离
// // // Draw the inlier points
// //cv::drawMatches(image1, keypoints1, // 1st image and its keypoints
// // image2, keypoints2, // 2nd image and its keypoints
// // matches, // the matches
// // imageMatches, // the image produced
// // cv::Scalar(255, 255, 255), // color of the lines
// // cv::Scalar(255, 255, 255), // color of the keypoints
// // inliers,
// // 2);
// //cv::namedWindow("Homography inlier points");
// //cv::imshow("Homography inlier points", imageMatches);
//
// ////将第一幅图像扭曲到第二幅图像----实现两幅图像的拼接
// //Mat result;
// //warpPerspective(image1, //输入图像
// // result, //输出图像
// // homography, //单应矩阵
// // Size(2 * image1.cols, image1.rows)); //输出图像的尺寸
//
// ////把第一幅图像复制到完整图像的第一个半边
// //Mat harf(result, Rect(0, 0, image2.cols, image2.rows));
// //image2.copyTo(harf); //把image2复制到image1的感兴趣区域
//
// //imshow("Image mosaic", result);
//
// ////图像拼接技术----用Stitcher生成全景图
// ////Mat img1 = imread("./images/parliament1.jpg");
// ////Mat img2 = imread("./images/parliament2.jpg");
// ////imshow("img1", img1);
// ////imshow("img2", img2);
// ////vector<Mat> images;
// ////images.push_back(img1);
// ////images.push_back(img2);
//
// //vector<Mat> images;
// //images.push_back(imread("./images/parliament1_1.jpg"));
// //images.push_back(imread("./images/parliament2_1.jpg"));
//
// //Mat panorama; //输出的全景图
// ////创建拼接器
// //Stitcher stitcher = Stitcher::createDefault();
// ////拼接图像
// //Stitcher::Status status = stitcher.stitch(images, panorama);
//
// //if (status == cv::Stitcher::OK) // success?
// //{
// //
// // cv::namedWindow("Panorama");
// // cv::imshow("Panorama", panorama);
// //}
//
//
//
// //4.检测图像中的平面目标
// // Read input images
// cv::Mat target = cv::imread("./images/cookbook1.bmp", 0);
// cv::Mat image = cv::imread("./images/objects.jpg", 0);
// if (!target.data || !image.data)
// return 0;
//
// // Display the images
// cv::namedWindow("Target");
// cv::imshow("Target", target);
// cv::namedWindow("Image");
// cv::imshow("Image", image);
//
// //初始化匹配器
// TargetMatcher tmatcher(FastFeatureDetector::create(10), BRISK::create());
// tmatcher.setNormType(NORM_HAMMING);
// //定义输出数据
// vector<DMatch> matches;
// vector<KeyPoint> keypoints1, keypoints2;
// vector<Point2f> corners;
// //设定目标图像
// tmatcher.setTarget(target);
// //匹配目标图像
// tmatcher.detectTarget(image, corners);
// //画出目标角点
// if (corners.size() == 4) { //已获得检测结果
//
// cv::line(image, cv::Point(corners[0]), cv::Point(corners[1]), cv::Scalar(255, 255, 255), 6);
// cv::line(image, cv::Point(corners[1]), cv::Point(corners[2]), cv::Scalar(255, 255, 255), 6);
// cv::line(image, cv::Point(corners[2]), cv::Point(corners[3]), cv::Scalar(255, 255, 255), 6);
// cv::line(image, cv::Point(corners[3]), cv::Point(corners[0]), cv::Scalar(255, 255, 255), 6);
// }
//
// cv::namedWindow("Target detection");
// cv::imshow("Target detection", image);
//
// waitKey(0);
// return 0;
//}
#pragma once
#if !defined MATCHER
#define MATCHER
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
using namespace std;
using namespace cv;
#define NOCHECK 0
#define CROSSCHECK 1
#define RATIOCHECK 2
#define BOTHCHECK 3
class RobustMatcher
{
private:
//特征点检测器对象的指针
Ptr<FeatureDetector> detector;
//特征描述子提取器对象的指针
Ptr<DescriptorExtractor> descriptor;
int normType;
float ratio; //第一个和第二个NN之间的最大比率
bool refineF; //如果等于true,则会优化基础矩阵
bool refineM; //如果等于true,则会优化匹配结果
double distance; //到极点的最小距离
double confidence; //可信度(概率)
public:
RobustMatcher(const cv::Ptr<cv::FeatureDetector> &detector,
const cv::Ptr<cv::DescriptorExtractor> &descriptor = cv::Ptr<cv::DescriptorExtractor>())
: detector(detector), descriptor(descriptor), normType(cv::NORM_L2),
ratio(0.8f), refineF(true), refineM(true), confidence(0.98), distance(1.0)
{
//这里使用关联描述子
if (!this->descriptor) {
this->descriptor = this->detector;
}
}
// Set the feature detector
void setFeatureDetector(const cv::Ptr<cv::FeatureDetector>& detect) {
this->detector = detect;
}
// Set descriptor extractor
void setDescriptorExtractor(const cv::Ptr<cv::DescriptorExtractor>& desc) {
this->descriptor = desc;
}
// Set the norm to be used for matching
void setNormType(int norm) {
normType = norm;
}
// Set the minimum distance to epipolar in RANSAC
void setMinDistanceToEpipolar(double d) {
distance = d;
}
// Set confidence level in RANSAC
void setConfidenceLevel(double c) {
confidence = c;
}
// Set the NN ratio
void setRatio(float r) {
ratio = r;
}
// if you want the F matrix to be recalculated
void refineFundamental(bool flag) {
refineF = flag;
}
// if you want the matches to be refined using F
void refineMatches(bool flag) {
refineM = flag;
}
// Clear matches for which NN ratio is > than threshold
// return the number of removed points
// (corresponding entries being cleared, i.e. size will be 0)
int ratioTest(const std::vector<std::vector<cv::DMatch> >& inputMatches,
std::vector<cv::DMatch>& outputMatches) {
int removed = 0;
// for all matches
for (std::vector<std::vector<cv::DMatch> >::const_iterator matchIterator = inputMatches.begin();
matchIterator != inputMatches.end(); ++matchIterator) {
// first best match/second best match
if ((matchIterator->size() > 1) && // if 2 NN has been identified
(*matchIterator)[0].distance / (*matchIterator)[1].distance < ratio) {
// it is an acceptable match
outputMatches.push_back((*matchIterator)[0]);
}
else {
removed++;
}
}
return removed;
}
// Insert symmetrical matches in symMatches vector
void symmetryTest(const std::vector<cv::DMatch>& matches1,
const std::vector<cv::DMatch>& matches2,
std::vector<cv::DMatch>& symMatches) {
// for all matches image 1 -> image 2
for (std::vector<cv::DMatch>::const_iterator matchIterator1 = matches1.begin();
matchIterator1 != matches1.end(); ++matchIterator1) {
// for all matches image 2 -> image 1
for (std::vector<cv::DMatch>::const_iterator matchIterator2 = matches2.begin();
matchIterator2 != matches2.end(); ++matchIterator2) {
// Match symmetry test
if (matchIterator1->queryIdx == matchIterator2->trainIdx &&
matchIterator2->queryIdx == matchIterator1->trainIdx) {
// add symmetrical match
symMatches.push_back(*matchIterator1);
break; // next match in image 1 -> image 2
}
}
}
}
// Apply both ratio and symmetry test
// (often an over-kill)
void ratioAndSymmetryTest(const std::vector<std::vector<cv::DMatch> >& matches1,
const std::vector<std::vector<cv::DMatch> >& matches2,
std::vector<cv::DMatch>& outputMatches) {
// Remove matches for which NN ratio is > than threshold
// clean image 1 -> image 2 matches
std::vector<cv::DMatch> ratioMatches1;
int removed = ratioTest(matches1, ratioMatches1);
std::cout << "Number of matched points 1->2 (ratio test) : " << ratioMatches1.size() << std::endl;
// clean image 2 -> image 1 matches
std::vector<cv::DMatch> ratioMatches2;
removed = ratioTest(matches2, ratioMatches2);
std::cout << "Number of matched points 1->2 (ratio test) : " << ratioMatches2.size() << std::endl;
// Remove non-symmetrical matches
symmetryTest(ratioMatches1, ratioMatches2, outputMatches);
std::cout << "Number of matched points (symmetry test): " << outputMatches.size() << std::endl;
}
// 用RANSAC算法获取优质匹配项
// 返回基础矩阵和匹配项
cv::Mat ransacTest(const std::vector<cv::DMatch>& matches,
std::vector<cv::KeyPoint>& keypoints1,
std::vector<cv::KeyPoint>& keypoints2,
std::vector<cv::DMatch>& outMatches) {
//把关键点转变为Point2f类型
std::vector<cv::Point2f> points1, points2;
for (std::vector<cv::DMatch>::const_iterator it = matches.begin();
it != matches.end(); ++it) {
//获取左侧关键点的位置
points1.push_back(keypoints1[it->queryIdx].pt);
//获取右侧关键点的位置
points2.push_back(keypoints2[it->trainIdx].pt);
}
// 用 RANSAC 计算F矩阵
std::vector<uchar> inliers(points1.size(), 0);
cv::Mat fundamental = cv::findFundamentalMat(
points1, points2, //匹配像素点
inliers, //匹配状态(inlier or outlier)
cv::FM_RANSAC, // RANSAC 算法
distance, // 到对极线的距离
confidence); // 置信度
//取下剩下的 (inliers) 匹配项
std::vector<uchar>::const_iterator itIn = inliers.begin();
std::vector<cv::DMatch>::const_iterator itM = matches.begin();
// 遍历所有的匹配项
for (; itIn != inliers.end(); ++itIn, ++itM) {
if (*itIn) { // it is a valid match
outMatches.push_back(*itM);
}
}
if (refineF || refineM) {
// The F matrix will be recomputed with all accepted matches
// Convert keypoints into Point2f for final F computation
points1.clear();
points2.clear();
for (std::vector<cv::DMatch>::const_iterator it = outMatches.begin();
it != outMatches.end(); ++it) {
// Get the position of left keypoints
points1.push_back(keypoints1[it->queryIdx].pt);
// Get the position of right keypoints
points2.push_back(keypoints2[it->trainIdx].pt);
}
// Compute 8-point F from all accepted matches
fundamental = cv::findFundamentalMat(
points1, points2, // matching points
cv::FM_8POINT); // 8-point method
if (refineM) {
std::vector<cv::Point2f> newPoints1, newPoints2;
// refine the matches
correctMatches(fundamental, // F matrix
points1, points2, // original position
newPoints1, newPoints2); // new position
for (int i = 0; i< points1.size(); i++) {
std::cout << "(" << keypoints1[outMatches[i].queryIdx].pt.x
<< "," << keypoints1[outMatches[i].queryIdx].pt.y
<< ") -> ";
std::cout << "(" << newPoints1[i].x
<< "," << newPoints1[i].y << std::endl;
std::cout << "(" << keypoints2[outMatches[i].trainIdx].pt.x
<< "," << keypoints2[outMatches[i].trainIdx].pt.y
<< ") -> ";
std::cout << "(" << newPoints2[i].x
<< "," << newPoints2[i].y << std::endl;
keypoints1[outMatches[i].queryIdx].pt.x = newPoints1[i].x;
keypoints1[outMatches[i].queryIdx].pt.y = newPoints1[i].y;
keypoints2[outMatches[i].trainIdx].pt.x = newPoints2[i].x;
keypoints2[outMatches[i].trainIdx].pt.y = newPoints2[i].y;
}
}
}
return fundamental;
}
//用RANSAC算法匹配特征点
//返回基础矩阵和输出的匹配项
//这是一个简单的展示,和书上的一样,下面有个比较复杂的
Mat matchBook(Mat &image1, Mat &image2, //输入图像
vector<DMatch> &matches, //输出匹配项
vector<KeyPoint> &keypoints1, //输出关键点
vector<KeyPoint> &keypoints2)
{
//1.检测特征点
detector->detect(image1, keypoints1);
detector->detect(image2, keypoints2);
//2.提取特征描述子
Mat descriptors1, descriptors2;
descriptor->compute(image1, keypoints1, descriptors1);
descriptor->compute(image2, keypoints2, descriptors2);
//3.匹配两幅图像描述子
//(用于部分检测方法)
//构造匹配类的实例(带交叉检查)
BFMatcher matcher(normType, //差距衡量
true); //交叉检查标志
//匹配描述子
vector<DMatch> outputMatches;
matcher.match(descriptors1, descriptors2, outputMatches);
//4.用RANSAC算法验证匹配项
Mat fundamental = ransacTest(outputMatches, keypoints1, keypoints2, matches);
//返回基础矩阵
return fundamental;
}
//用RANSAC算法匹配特征点
//返回基础矩阵和输出的匹配项
cv::Mat match(cv::Mat& image1, cv::Mat& image2, // 输入图像
std::vector<cv::DMatch>& matches, // 输出匹配项和关键点
std::vector<cv::KeyPoint>& keypoints1, std::vector<cv::KeyPoint>& keypoints2,
int check = CROSSCHECK) { // check type (symmetry or ratio or none or both)
//检测特征点
detector->detect(image1, keypoints1);
detector->detect(image2, keypoints2);
std::cout << "Number of feature points (1): " << keypoints1.size() << std::endl;
std::cout << "Number of feature points (2): " << keypoints2.size() << std::endl;
// 提取特征描述子
cv::Mat descriptors1, descriptors2;
descriptor->compute(image1, keypoints1, descriptors1);
descriptor->compute(image2, keypoints2, descriptors2);
std::cout << "descriptor matrix size: " << descriptors1.rows << " by " << descriptors1.cols << std::endl;
// 3. Match the two image descriptors
// (optionaly apply some checking method)
// Construction of the matcher with crosscheck
cv::BFMatcher matcher(normType, //distance measure
check == CROSSCHECK); // crosscheck flag
// vectors of matches
std::vector<std::vector<cv::DMatch> > matches1;
std::vector<std::vector<cv::DMatch> > matches2;
std::vector<cv::DMatch> outputMatches;
// call knnMatch if ratio check is required
if (check == RATIOCHECK || check == BOTHCHECK) {
// from image 1 to image 2
// based on k nearest neighbours (with k=2)
matcher.knnMatch(descriptors1, descriptors2,
matches1, // vector of matches (up to 2 per entry)
2); // return 2 nearest neighbours
std::cout << "Number of matched points 1->2: " << matches1.size() << std::endl;
if (check == BOTHCHECK) {
// from image 2 to image 1
// based on k nearest neighbours (with k=2)
matcher.knnMatch(descriptors2, descriptors1,
matches2, // vector of matches (up to 2 per entry)
2); // return 2 nearest neighbours
std::cout << "Number of matched points 2->1: " << matches2.size() << std::endl;
}
}
// select check method
switch (check) {
case CROSSCHECK:
matcher.match(descriptors1, descriptors2, outputMatches);
std::cout << "Number of matched points 1->2 (after cross-check): " << outputMatches.size() << std::endl;
break;
case RATIOCHECK:
ratioTest(matches1, outputMatches);
std::cout << "Number of matched points 1->2 (after ratio test): " << outputMatches.size() << std::endl;
break;
case BOTHCHECK:
ratioAndSymmetryTest(matches1, matches2, outputMatches);
std::cout << "Number of matched points 1->2 (after ratio and cross-check): " << outputMatches.size() << std::endl;
break;
case NOCHECK:
default:
matcher.match(descriptors1, descriptors2, outputMatches);
std::cout << "Number of matched points 1->2: " << outputMatches.size() << std::endl;
break;
}
// 4. Validate matches using RANSAC
cv::Mat fundamental = ransacTest(outputMatches, keypoints1, keypoints2, matches);
std::cout << "Number of matched points (after RANSAC): " << matches.size() << std::endl;
// return the found fundamental matrix
return fundamental;
}
};
#endif // !define MATCHER
#pragma once
#if !defined TMATCHER
#define TMATCHER
#define VERBOSE 1
#include <iostream>
#include <vector>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/features2d.hpp>
using namespace std;
using namespace cv;
class TargetMatcher
{
private:
//特征点检测器对象的指针
Ptr<FeatureDetector> detector;
//特征描述子提取器对象的指针
Ptr<DescriptorExtractor> descriptor;
//目标图像
Mat target;
//比较描述子容器
int normType;
//最小重投影误差
double distance;
//金字塔形图像的数量
int numberOfLevels;
//层级之间的范围
double scaleFactor;
//目标图像构建的金字塔以及它的关键点
vector<Mat> pyramid;
vector<vector<KeyPoint> > pyrKeypoints;
vector<Mat> pyrDescriptors;
// 创建目标图像的金字塔
void createPyramid() {
// 创建目标图像的金字塔
pyramid.clear();
cv::Mat layer(target);
for (int i = 0; i < numberOfLevels; i++) { // 逐层缩小
pyramid.push_back(target.clone());
resize(target, target, cv::Size(), scaleFactor, scaleFactor);
}
pyrKeypoints.clear();
pyrDescriptors.clear();
// 逐层检测关键点和描述子
for (int i = 0; i < numberOfLevels; i++) {
// 在第i层检测目标关键点
pyrKeypoints.push_back(std::vector<cv::KeyPoint>());
detector->detect(pyramid[i], pyrKeypoints[i]);
if (VERBOSE)
std::cout << "Interest points: target=" << pyrKeypoints[i].size() << std::endl;
//在第i层计算描述子
pyrDescriptors.push_back(cv::Mat());
descriptor->compute(pyramid[i], pyrKeypoints[i], pyrDescriptors[i]);
}
}
public:
TargetMatcher(const cv::Ptr<cv::FeatureDetector> &detector,
const cv::Ptr<cv::DescriptorExtractor> &descriptor = cv::Ptr<cv::DescriptorExtractor>(),
int numberOfLevels = 8, double scaleFactor = 0.9)
: detector(detector), descriptor(descriptor), normType(cv::NORM_L2), distance(1.0),
numberOfLevels(numberOfLevels), scaleFactor(scaleFactor) {
// in this case use the associated descriptor
if (!this->descriptor) {
this->descriptor = this->detector;
}
}
// Set the norm to be used for matching
void setNormType(int norm) {
normType = norm;
}
// Set the minimum reprojection distance
void setReprojectionDistance(double d) {
distance = d;
}
//设置目标图像
void setTarget(const Mat t)
{
if (VERBOSE)
cv::imshow("Target", t);
target = t;
createPyramid();
}
// Identify good matches using RANSAC
// Return homography matrix and output matches
//下面的是更好的
cv::Mat ransacTest(const std::vector<cv::DMatch>& matches,
std::vector<cv::KeyPoint>& keypoints1,
std::vector<cv::KeyPoint>& keypoints2,
std::vector<cv::DMatch>& outMatches) {
// Convert keypoints into Point2f
std::vector<cv::Point2f> points1, points2;
outMatches.clear();
for (std::vector<cv::DMatch>::const_iterator it = matches.begin();
it != matches.end(); ++it) {
// Get the position of left keypoints
points1.push_back(keypoints1[it->queryIdx].pt);
// Get the position of right keypoints
points2.push_back(keypoints2[it->trainIdx].pt);
}
// Find the homography between image 1 and image 2
std::vector<uchar> inliers(points1.size(), 0);
cv::Mat homography = cv::findHomography(
points1, points2, // corresponding points
inliers, // match status (inlier or outlier)
cv::RHO, // RHO method
distance); // max distance to reprojection point
// extract the surviving (inliers) matches
std::vector<uchar>::const_iterator itIn = inliers.begin();
std::vector<cv::DMatch>::const_iterator itM = matches.begin();
// for all matches
for (; itIn != inliers.end(); ++itIn, ++itM) {
if (*itIn) { // it is a valid match
outMatches.push_back(*itM);
}
}
return homography;
}
// 检测预先定义的平面目标
// 返回单应矩阵和检测到的目标的4个角点
cv::Mat detectTarget(const cv::Mat& image,
// 目标角点的坐标(顺时针方向)
std::vector<cv::Point2f>& detectedCorners) {
// 1. 检测图像的关键点
std::vector<cv::KeyPoint> keypoints;
detector->detect(image, keypoints);
if (VERBOSE)
std::cout << "Interest points: image=" << keypoints.size() << std::endl;
// 计算描述子
cv::Mat descriptors;
descriptor->compute(image, keypoints, descriptors);
std::vector<cv::DMatch> matches;
cv::Mat bestHomography;
cv::Size bestSize;
int maxInliers = 0;
cv::Mat homography;
// 构建匹配器
cv::BFMatcher matcher(normType);
// 2. 对金字塔的每层, 鲁棒匹配单应矩阵
for (int i = 0; i < numberOfLevels; i++) {
// 在目标和图像之间发现RANSAC单应矩阵
matches.clear();
// 匹配描述子
matcher.match(pyrDescriptors[i], descriptors, matches);
if (VERBOSE)
std::cout << "Number of matches (level " << i << ")=" << matches.size() << std::endl;
// 用RANSAC验证匹配项
std::vector<cv::DMatch> inliers;
homography = ransacTest(matches, pyrKeypoints[i], keypoints, inliers);
if (VERBOSE)
std::cout << "Number of inliers=" << inliers.size() << std::endl;
if (inliers.size() > maxInliers) { // 有更好的 H
maxInliers = inliers.size();
bestHomography = homography;
bestSize = pyramid[i].size();
}
if (VERBOSE) {
cv::Mat imageMatches;
cv::drawMatches(target, pyrKeypoints[i], // 1st image and its keypoints
image, keypoints, // 2nd image and its keypoints
inliers, // the matches
imageMatches, // the image produced
cv::Scalar(255, 255, 255), // color of the lines
cv::Scalar(255, 255, 255), // color of the keypoints
std::vector<char>(),
2);
cv::imshow("Target matches", imageMatches);
cv::waitKey();
}
}
// 3. 用最佳单应矩阵找出角点坐标
if (maxInliers > 8) { // 估计值有效
//最佳尺寸的目标角点
std::vector<cv::Point2f> corners;
corners.push_back(cv::Point2f(0, 0));
corners.push_back(cv::Point2f(bestSize.width - 1, 0));
corners.push_back(cv::Point2f(bestSize.width - 1, bestSize.height - 1));
corners.push_back(cv::Point2f(0, bestSize.height - 1));
// 重新投影目标角点
cv::perspectiveTransform(corners, detectedCorners, bestHomography);
}
if (VERBOSE)
std::cout << "Best number of inliers=" << maxInliers << std::endl;
return bestHomography;
}
};
#endif // !defined TMATCHER
|