Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/stitching/src/matchers.cpp
16337 views
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
8
//
9
//
10
// License Agreement
11
// For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15
// Third party copyrights are property of their respective owners.
16
//
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
19
//
20
// * Redistribution's of source code must retain the above copyright notice,
21
// this list of conditions and the following disclaimer.
22
//
23
// * Redistribution's in binary form must reproduce the above copyright notice,
24
// this list of conditions and the following disclaimer in the documentation
25
// and/or other materials provided with the distribution.
26
//
27
// * The name of the copyright holders may not be used to endorse or promote products
28
// derived from this software without specific prior written permission.
29
//
30
// This software is provided by the copyright holders and contributors "as is" and
31
// any express or implied warranties, including, but not limited to, the implied
32
// warranties of merchantability and fitness for a particular purpose are disclaimed.
33
// In no event shall the Intel Corporation or contributors be liable for any direct,
34
// indirect, incidental, special, exemplary, or consequential damages
35
// (including, but not limited to, procurement of substitute goods or services;
36
// loss of use, data, or profits; or business interruption) however caused
37
// and on any theory of liability, whether in contract, strict liability,
38
// or tort (including negligence or otherwise) arising in any way out of
39
// the use of this software, even if advised of the possibility of such damage.
40
//
41
//M*/
42
43
#include "precomp.hpp"
44
45
#include "opencv2/core/opencl/ocl_defs.hpp"
46
47
using namespace cv;
48
using namespace cv::detail;
49
using namespace cv::cuda;
50
51
#ifdef HAVE_OPENCV_XFEATURES2D
52
#include "opencv2/xfeatures2d.hpp"
53
using xfeatures2d::SURF;
54
using xfeatures2d::SIFT;
55
#else
56
# if defined(_MSC_VER)
57
# pragma warning(disable:4702) // unreachable code
58
# endif
59
#endif
60
61
#ifdef HAVE_OPENCV_CUDAIMGPROC
62
# include "opencv2/cudaimgproc.hpp"
63
#endif
64
65
namespace {
66
67
struct DistIdxPair
68
{
69
bool operator<(const DistIdxPair &other) const { return dist < other.dist; }
70
double dist;
71
int idx;
72
};
73
74
75
struct MatchPairsBody : ParallelLoopBody
76
{
77
MatchPairsBody(FeaturesMatcher &_matcher, const std::vector<ImageFeatures> &_features,
78
std::vector<MatchesInfo> &_pairwise_matches, std::vector<std::pair<int,int> > &_near_pairs)
79
: matcher(_matcher), features(_features),
80
pairwise_matches(_pairwise_matches), near_pairs(_near_pairs) {}
81
82
void operator ()(const Range &r) const CV_OVERRIDE
83
{
84
cv::RNG rng = cv::theRNG(); // save entry rng state
85
const int num_images = static_cast<int>(features.size());
86
for (int i = r.start; i < r.end; ++i)
87
{
88
cv::theRNG() = cv::RNG(rng.state + i); // force "stable" RNG seed for each processed pair
89
90
int from = near_pairs[i].first;
91
int to = near_pairs[i].second;
92
int pair_idx = from*num_images + to;
93
94
matcher(features[from], features[to], pairwise_matches[pair_idx]);
95
pairwise_matches[pair_idx].src_img_idx = from;
96
pairwise_matches[pair_idx].dst_img_idx = to;
97
98
size_t dual_pair_idx = to*num_images + from;
99
100
pairwise_matches[dual_pair_idx] = pairwise_matches[pair_idx];
101
pairwise_matches[dual_pair_idx].src_img_idx = to;
102
pairwise_matches[dual_pair_idx].dst_img_idx = from;
103
104
if (!pairwise_matches[pair_idx].H.empty())
105
pairwise_matches[dual_pair_idx].H = pairwise_matches[pair_idx].H.inv();
106
107
for (size_t j = 0; j < pairwise_matches[dual_pair_idx].matches.size(); ++j)
108
std::swap(pairwise_matches[dual_pair_idx].matches[j].queryIdx,
109
pairwise_matches[dual_pair_idx].matches[j].trainIdx);
110
LOG(".");
111
}
112
}
113
114
FeaturesMatcher &matcher;
115
const std::vector<ImageFeatures> &features;
116
std::vector<MatchesInfo> &pairwise_matches;
117
std::vector<std::pair<int,int> > &near_pairs;
118
119
private:
120
void operator =(const MatchPairsBody&);
121
};
122
123
124
struct FindFeaturesBody : ParallelLoopBody
125
{
126
FindFeaturesBody(FeaturesFinder &finder, InputArrayOfArrays images,
127
std::vector<ImageFeatures> &features, const std::vector<std::vector<cv::Rect> > *rois)
128
: finder_(finder), images_(images), features_(features), rois_(rois) {}
129
130
void operator ()(const Range &r) const CV_OVERRIDE
131
{
132
for (int i = r.start; i < r.end; ++i)
133
{
134
Mat image = images_.getMat(i);
135
if (rois_)
136
finder_(image, features_[i], (*rois_)[i]);
137
else
138
finder_(image, features_[i]);
139
}
140
}
141
142
private:
143
FeaturesFinder &finder_;
144
InputArrayOfArrays images_;
145
std::vector<ImageFeatures> &features_;
146
const std::vector<std::vector<cv::Rect> > *rois_;
147
148
// to cease visual studio warning
149
void operator =(const FindFeaturesBody&);
150
};
151
152
153
//////////////////////////////////////////////////////////////////////////////
154
155
typedef std::set<std::pair<int,int> > MatchesSet;
156
157
// These two classes are aimed to find features matches only, not to
158
// estimate homography
159
160
class CpuMatcher CV_FINAL : public FeaturesMatcher
161
{
162
public:
163
CpuMatcher(float match_conf) : FeaturesMatcher(true), match_conf_(match_conf) {}
164
void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info) CV_OVERRIDE;
165
166
private:
167
float match_conf_;
168
};
169
170
#ifdef HAVE_OPENCV_CUDAFEATURES2D
171
class GpuMatcher CV_FINAL : public FeaturesMatcher
172
{
173
public:
174
GpuMatcher(float match_conf) : match_conf_(match_conf) {}
175
void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info);
176
177
void collectGarbage();
178
179
private:
180
float match_conf_;
181
GpuMat descriptors1_, descriptors2_;
182
GpuMat train_idx_, distance_, all_dist_;
183
std::vector< std::vector<DMatch> > pair_matches;
184
};
185
#endif
186
187
188
void CpuMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info)
189
{
190
CV_INSTRUMENT_REGION();
191
192
CV_Assert(features1.descriptors.type() == features2.descriptors.type());
193
CV_Assert(features2.descriptors.depth() == CV_8U || features2.descriptors.depth() == CV_32F);
194
195
matches_info.matches.clear();
196
197
Ptr<cv::DescriptorMatcher> matcher;
198
#if 0 // TODO check this
199
if (ocl::isOpenCLActivated())
200
{
201
matcher = makePtr<BFMatcher>((int)NORM_L2);
202
}
203
else
204
#endif
205
{
206
Ptr<flann::IndexParams> indexParams = makePtr<flann::KDTreeIndexParams>();
207
Ptr<flann::SearchParams> searchParams = makePtr<flann::SearchParams>();
208
209
if (features2.descriptors.depth() == CV_8U)
210
{
211
indexParams->setAlgorithm(cvflann::FLANN_INDEX_LSH);
212
searchParams->setAlgorithm(cvflann::FLANN_INDEX_LSH);
213
}
214
215
matcher = makePtr<FlannBasedMatcher>(indexParams, searchParams);
216
}
217
std::vector< std::vector<DMatch> > pair_matches;
218
MatchesSet matches;
219
220
// Find 1->2 matches
221
matcher->knnMatch(features1.descriptors, features2.descriptors, pair_matches, 2);
222
for (size_t i = 0; i < pair_matches.size(); ++i)
223
{
224
if (pair_matches[i].size() < 2)
225
continue;
226
const DMatch& m0 = pair_matches[i][0];
227
const DMatch& m1 = pair_matches[i][1];
228
if (m0.distance < (1.f - match_conf_) * m1.distance)
229
{
230
matches_info.matches.push_back(m0);
231
matches.insert(std::make_pair(m0.queryIdx, m0.trainIdx));
232
}
233
}
234
LOG("\n1->2 matches: " << matches_info.matches.size() << endl);
235
236
// Find 2->1 matches
237
pair_matches.clear();
238
matcher->knnMatch(features2.descriptors, features1.descriptors, pair_matches, 2);
239
for (size_t i = 0; i < pair_matches.size(); ++i)
240
{
241
if (pair_matches[i].size() < 2)
242
continue;
243
const DMatch& m0 = pair_matches[i][0];
244
const DMatch& m1 = pair_matches[i][1];
245
if (m0.distance < (1.f - match_conf_) * m1.distance)
246
if (matches.find(std::make_pair(m0.trainIdx, m0.queryIdx)) == matches.end())
247
matches_info.matches.push_back(DMatch(m0.trainIdx, m0.queryIdx, m0.distance));
248
}
249
LOG("1->2 & 2->1 matches: " << matches_info.matches.size() << endl);
250
}
251
252
#ifdef HAVE_OPENCV_CUDAFEATURES2D
253
void GpuMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info)
254
{
255
CV_INSTRUMENT_REGION();
256
257
matches_info.matches.clear();
258
259
ensureSizeIsEnough(features1.descriptors.size(), features1.descriptors.type(), descriptors1_);
260
ensureSizeIsEnough(features2.descriptors.size(), features2.descriptors.type(), descriptors2_);
261
262
descriptors1_.upload(features1.descriptors);
263
descriptors2_.upload(features2.descriptors);
264
265
//TODO: NORM_L1 allows to avoid matcher crashes for ORB features, but is not absolutely correct for them.
266
// The best choice for ORB features is NORM_HAMMING, but it is incorrect for SURF features.
267
// More accurate fix in this place should be done in the future -- the type of the norm
268
// should be either a parameter of this method, or a field of the class.
269
Ptr<cuda::DescriptorMatcher> matcher = cuda::DescriptorMatcher::createBFMatcher(NORM_L1);
270
271
MatchesSet matches;
272
273
// Find 1->2 matches
274
pair_matches.clear();
275
matcher->knnMatch(descriptors1_, descriptors2_, pair_matches, 2);
276
for (size_t i = 0; i < pair_matches.size(); ++i)
277
{
278
if (pair_matches[i].size() < 2)
279
continue;
280
const DMatch& m0 = pair_matches[i][0];
281
const DMatch& m1 = pair_matches[i][1];
282
if (m0.distance < (1.f - match_conf_) * m1.distance)
283
{
284
matches_info.matches.push_back(m0);
285
matches.insert(std::make_pair(m0.queryIdx, m0.trainIdx));
286
}
287
}
288
289
// Find 2->1 matches
290
pair_matches.clear();
291
matcher->knnMatch(descriptors2_, descriptors1_, pair_matches, 2);
292
for (size_t i = 0; i < pair_matches.size(); ++i)
293
{
294
if (pair_matches[i].size() < 2)
295
continue;
296
const DMatch& m0 = pair_matches[i][0];
297
const DMatch& m1 = pair_matches[i][1];
298
if (m0.distance < (1.f - match_conf_) * m1.distance)
299
if (matches.find(std::make_pair(m0.trainIdx, m0.queryIdx)) == matches.end())
300
matches_info.matches.push_back(DMatch(m0.trainIdx, m0.queryIdx, m0.distance));
301
}
302
}
303
304
void GpuMatcher::collectGarbage()
305
{
306
descriptors1_.release();
307
descriptors2_.release();
308
train_idx_.release();
309
distance_.release();
310
all_dist_.release();
311
std::vector< std::vector<DMatch> >().swap(pair_matches);
312
}
313
#endif
314
315
} // namespace
316
317
318
namespace cv {
319
namespace detail {
320
321
void FeaturesFinder::operator ()(InputArray image, ImageFeatures &features)
322
{
323
find(image, features);
324
features.img_size = image.size();
325
}
326
327
328
void FeaturesFinder::operator ()(InputArray image, ImageFeatures &features, const std::vector<Rect> &rois)
329
{
330
std::vector<ImageFeatures> roi_features(rois.size());
331
size_t total_kps_count = 0;
332
int total_descriptors_height = 0;
333
334
for (size_t i = 0; i < rois.size(); ++i)
335
{
336
find(image.getUMat()(rois[i]), roi_features[i]);
337
total_kps_count += roi_features[i].keypoints.size();
338
total_descriptors_height += roi_features[i].descriptors.rows;
339
}
340
341
features.img_size = image.size();
342
features.keypoints.resize(total_kps_count);
343
features.descriptors.create(total_descriptors_height,
344
roi_features[0].descriptors.cols,
345
roi_features[0].descriptors.type());
346
347
int kp_idx = 0;
348
int descr_offset = 0;
349
for (size_t i = 0; i < rois.size(); ++i)
350
{
351
for (size_t j = 0; j < roi_features[i].keypoints.size(); ++j, ++kp_idx)
352
{
353
features.keypoints[kp_idx] = roi_features[i].keypoints[j];
354
features.keypoints[kp_idx].pt.x += (float)rois[i].x;
355
features.keypoints[kp_idx].pt.y += (float)rois[i].y;
356
}
357
UMat subdescr = features.descriptors.rowRange(
358
descr_offset, descr_offset + roi_features[i].descriptors.rows);
359
roi_features[i].descriptors.copyTo(subdescr);
360
descr_offset += roi_features[i].descriptors.rows;
361
}
362
}
363
364
365
void FeaturesFinder::operator ()(InputArrayOfArrays images, std::vector<ImageFeatures> &features)
366
{
367
size_t count = images.total();
368
features.resize(count);
369
370
FindFeaturesBody body(*this, images, features, NULL);
371
if (isThreadSafe())
372
parallel_for_(Range(0, static_cast<int>(count)), body);
373
else
374
body(Range(0, static_cast<int>(count)));
375
}
376
377
378
void FeaturesFinder::operator ()(InputArrayOfArrays images, std::vector<ImageFeatures> &features,
379
const std::vector<std::vector<cv::Rect> > &rois)
380
{
381
CV_Assert(rois.size() == images.total());
382
size_t count = images.total();
383
features.resize(count);
384
385
FindFeaturesBody body(*this, images, features, &rois);
386
if (isThreadSafe())
387
parallel_for_(Range(0, static_cast<int>(count)), body);
388
else
389
body(Range(0, static_cast<int>(count)));
390
}
391
392
393
bool FeaturesFinder::isThreadSafe() const
394
{
395
#ifdef HAVE_OPENCL
396
if (ocl::isOpenCLActivated())
397
{
398
return false;
399
}
400
#endif
401
if (dynamic_cast<const SurfFeaturesFinder*>(this))
402
{
403
return true;
404
}
405
else if (dynamic_cast<const OrbFeaturesFinder*>(this))
406
{
407
return true;
408
}
409
else
410
{
411
return false;
412
}
413
}
414
415
416
SurfFeaturesFinder::SurfFeaturesFinder(double hess_thresh, int num_octaves, int num_layers,
417
int num_octaves_descr, int num_layers_descr)
418
{
419
#ifdef HAVE_OPENCV_XFEATURES2D
420
if (num_octaves_descr == num_octaves && num_layers_descr == num_layers)
421
{
422
Ptr<SURF> surf_ = SURF::create();
423
if( !surf_ )
424
CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" );
425
surf_->setHessianThreshold(hess_thresh);
426
surf_->setNOctaves(num_octaves);
427
surf_->setNOctaveLayers(num_layers);
428
surf = surf_;
429
}
430
else
431
{
432
Ptr<SURF> sdetector_ = SURF::create();
433
Ptr<SURF> sextractor_ = SURF::create();
434
435
if( !sdetector_ || !sextractor_ )
436
CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" );
437
438
sdetector_->setHessianThreshold(hess_thresh);
439
sdetector_->setNOctaves(num_octaves);
440
sdetector_->setNOctaveLayers(num_layers);
441
442
sextractor_->setNOctaves(num_octaves_descr);
443
sextractor_->setNOctaveLayers(num_layers_descr);
444
445
detector_ = sdetector_;
446
extractor_ = sextractor_;
447
}
448
#else
449
CV_UNUSED(hess_thresh);
450
CV_UNUSED(num_octaves);
451
CV_UNUSED(num_layers);
452
CV_UNUSED(num_octaves_descr);
453
CV_UNUSED(num_layers_descr);
454
CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" );
455
#endif
456
}
457
458
void SurfFeaturesFinder::find(InputArray image, ImageFeatures &features)
459
{
460
UMat gray_image;
461
CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC1));
462
if(image.type() == CV_8UC3)
463
{
464
cvtColor(image, gray_image, COLOR_BGR2GRAY);
465
}
466
else
467
{
468
gray_image = image.getUMat();
469
}
470
if (!surf)
471
{
472
detector_->detect(gray_image, features.keypoints);
473
extractor_->compute(gray_image, features.keypoints, features.descriptors);
474
}
475
else
476
{
477
UMat descriptors;
478
surf->detectAndCompute(gray_image, Mat(), features.keypoints, descriptors);
479
features.descriptors = descriptors.reshape(1, (int)features.keypoints.size());
480
}
481
}
482
483
SiftFeaturesFinder::SiftFeaturesFinder()
484
{
485
#ifdef HAVE_OPENCV_XFEATURES2D
486
Ptr<SIFT> sift_ = SIFT::create();
487
if( !sift_ )
488
CV_Error( Error::StsNotImplemented, "OpenCV was built without SIFT support" );
489
sift = sift_;
490
#else
491
CV_Error( Error::StsNotImplemented, "OpenCV was built without SIFT support" );
492
#endif
493
}
494
495
void SiftFeaturesFinder::find(InputArray image, ImageFeatures &features)
496
{
497
UMat gray_image;
498
CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC1));
499
if(image.type() == CV_8UC3)
500
{
501
cvtColor(image, gray_image, COLOR_BGR2GRAY);
502
}
503
else
504
{
505
gray_image = image.getUMat();
506
}
507
UMat descriptors;
508
sift->detectAndCompute(gray_image, Mat(), features.keypoints, descriptors);
509
features.descriptors = descriptors.reshape(1, (int)features.keypoints.size());
510
}
511
512
OrbFeaturesFinder::OrbFeaturesFinder(Size _grid_size, int n_features, float scaleFactor, int nlevels)
513
{
514
grid_size = _grid_size;
515
orb = ORB::create(n_features * (99 + grid_size.area())/100/grid_size.area(), scaleFactor, nlevels);
516
}
517
518
void OrbFeaturesFinder::find(InputArray image, ImageFeatures &features)
519
{
520
UMat gray_image;
521
522
CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC4) || (image.type() == CV_8UC1));
523
524
if (image.type() == CV_8UC3) {
525
cvtColor(image, gray_image, COLOR_BGR2GRAY);
526
} else if (image.type() == CV_8UC4) {
527
cvtColor(image, gray_image, COLOR_BGRA2GRAY);
528
} else if (image.type() == CV_8UC1) {
529
gray_image = image.getUMat();
530
} else {
531
CV_Error(Error::StsUnsupportedFormat, "");
532
}
533
534
if (grid_size.area() == 1)
535
orb->detectAndCompute(gray_image, Mat(), features.keypoints, features.descriptors);
536
else
537
{
538
features.keypoints.clear();
539
features.descriptors.release();
540
541
std::vector<KeyPoint> points;
542
Mat _descriptors;
543
UMat descriptors;
544
545
for (int r = 0; r < grid_size.height; ++r)
546
for (int c = 0; c < grid_size.width; ++c)
547
{
548
int xl = c * gray_image.cols / grid_size.width;
549
int yl = r * gray_image.rows / grid_size.height;
550
int xr = (c+1) * gray_image.cols / grid_size.width;
551
int yr = (r+1) * gray_image.rows / grid_size.height;
552
553
// LOGLN("OrbFeaturesFinder::find: gray_image.empty=" << (gray_image.empty()?"true":"false") << ", "
554
// << " gray_image.size()=(" << gray_image.size().width << "x" << gray_image.size().height << "), "
555
// << " yl=" << yl << ", yr=" << yr << ", "
556
// << " xl=" << xl << ", xr=" << xr << ", gray_image.data=" << ((size_t)gray_image.data) << ", "
557
// << "gray_image.dims=" << gray_image.dims << "\n");
558
559
UMat gray_image_part=gray_image(Range(yl, yr), Range(xl, xr));
560
// LOGLN("OrbFeaturesFinder::find: gray_image_part.empty=" << (gray_image_part.empty()?"true":"false") << ", "
561
// << " gray_image_part.size()=(" << gray_image_part.size().width << "x" << gray_image_part.size().height << "), "
562
// << " gray_image_part.dims=" << gray_image_part.dims << ", "
563
// << " gray_image_part.data=" << ((size_t)gray_image_part.data) << "\n");
564
565
orb->detectAndCompute(gray_image_part, UMat(), points, descriptors);
566
567
features.keypoints.reserve(features.keypoints.size() + points.size());
568
for (std::vector<KeyPoint>::iterator kp = points.begin(); kp != points.end(); ++kp)
569
{
570
kp->pt.x += xl;
571
kp->pt.y += yl;
572
features.keypoints.push_back(*kp);
573
}
574
_descriptors.push_back(descriptors.getMat(ACCESS_READ));
575
}
576
577
// TODO optimize copyTo()
578
//features.descriptors = _descriptors.getUMat(ACCESS_READ);
579
_descriptors.copyTo(features.descriptors);
580
}
581
}
582
583
AKAZEFeaturesFinder::AKAZEFeaturesFinder(AKAZE::DescriptorType descriptor_type,
584
int descriptor_size,
585
int descriptor_channels,
586
float threshold,
587
int nOctaves,
588
int nOctaveLayers,
589
KAZE::DiffusivityType diffusivity)
590
{
591
akaze = AKAZE::create(descriptor_type, descriptor_size, descriptor_channels,
592
threshold, nOctaves, nOctaveLayers, diffusivity);
593
}
594
595
void AKAZEFeaturesFinder::find(InputArray image, detail::ImageFeatures &features)
596
{
597
CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC1));
598
akaze->detectAndCompute(image, noArray(), features.keypoints, features.descriptors);
599
}
600
601
#ifdef HAVE_OPENCV_XFEATURES2D
602
SurfFeaturesFinderGpu::SurfFeaturesFinderGpu(double hess_thresh, int num_octaves, int num_layers,
603
int num_octaves_descr, int num_layers_descr)
604
{
605
surf_.keypointsRatio = 0.1f;
606
surf_.hessianThreshold = hess_thresh;
607
surf_.extended = false;
608
num_octaves_ = num_octaves;
609
num_layers_ = num_layers;
610
num_octaves_descr_ = num_octaves_descr;
611
num_layers_descr_ = num_layers_descr;
612
}
613
614
615
void SurfFeaturesFinderGpu::find(InputArray image, ImageFeatures &features)
616
{
617
CV_Assert(image.depth() == CV_8U);
618
619
ensureSizeIsEnough(image.size(), image.type(), image_);
620
image_.upload(image);
621
622
ensureSizeIsEnough(image.size(), CV_8UC1, gray_image_);
623
624
#ifdef HAVE_OPENCV_CUDAIMGPROC
625
cv::cuda::cvtColor(image_, gray_image_, COLOR_BGR2GRAY);
626
#else
627
cvtColor(image_, gray_image_, COLOR_BGR2GRAY);
628
#endif
629
630
surf_.nOctaves = num_octaves_;
631
surf_.nOctaveLayers = num_layers_;
632
surf_.upright = false;
633
surf_(gray_image_, GpuMat(), keypoints_);
634
635
surf_.nOctaves = num_octaves_descr_;
636
surf_.nOctaveLayers = num_layers_descr_;
637
surf_.upright = true;
638
surf_(gray_image_, GpuMat(), keypoints_, descriptors_, true);
639
surf_.downloadKeypoints(keypoints_, features.keypoints);
640
641
descriptors_.download(features.descriptors);
642
}
643
644
void SurfFeaturesFinderGpu::collectGarbage()
645
{
646
surf_.releaseMemory();
647
image_.release();
648
gray_image_.release();
649
keypoints_.release();
650
descriptors_.release();
651
}
652
#endif
653
654
655
//////////////////////////////////////////////////////////////////////////////
656
657
MatchesInfo::MatchesInfo() : src_img_idx(-1), dst_img_idx(-1), num_inliers(0), confidence(0) {}
658
659
MatchesInfo::MatchesInfo(const MatchesInfo &other) { *this = other; }
660
661
MatchesInfo& MatchesInfo::operator =(const MatchesInfo &other)
662
{
663
src_img_idx = other.src_img_idx;
664
dst_img_idx = other.dst_img_idx;
665
matches = other.matches;
666
inliers_mask = other.inliers_mask;
667
num_inliers = other.num_inliers;
668
H = other.H.clone();
669
confidence = other.confidence;
670
return *this;
671
}
672
673
674
//////////////////////////////////////////////////////////////////////////////
675
676
void FeaturesMatcher::operator ()(const std::vector<ImageFeatures> &features, std::vector<MatchesInfo> &pairwise_matches,
677
const UMat &mask)
678
{
679
const int num_images = static_cast<int>(features.size());
680
681
CV_Assert(mask.empty() || (mask.type() == CV_8U && mask.cols == num_images && mask.rows));
682
Mat_<uchar> mask_(mask.getMat(ACCESS_READ));
683
if (mask_.empty())
684
mask_ = Mat::ones(num_images, num_images, CV_8U);
685
686
std::vector<std::pair<int,int> > near_pairs;
687
for (int i = 0; i < num_images - 1; ++i)
688
for (int j = i + 1; j < num_images; ++j)
689
if (features[i].keypoints.size() > 0 && features[j].keypoints.size() > 0 && mask_(i, j))
690
near_pairs.push_back(std::make_pair(i, j));
691
692
pairwise_matches.resize(num_images * num_images);
693
MatchPairsBody body(*this, features, pairwise_matches, near_pairs);
694
695
if (is_thread_safe_)
696
parallel_for_(Range(0, static_cast<int>(near_pairs.size())), body);
697
else
698
body(Range(0, static_cast<int>(near_pairs.size())));
699
LOGLN_CHAT("");
700
}
701
702
703
//////////////////////////////////////////////////////////////////////////////
704
705
BestOf2NearestMatcher::BestOf2NearestMatcher(bool try_use_gpu, float match_conf, int num_matches_thresh1, int num_matches_thresh2)
706
{
707
CV_UNUSED(try_use_gpu);
708
709
#ifdef HAVE_OPENCV_CUDAFEATURES2D
710
if (try_use_gpu && getCudaEnabledDeviceCount() > 0)
711
{
712
impl_ = makePtr<GpuMatcher>(match_conf);
713
}
714
else
715
#endif
716
{
717
impl_ = makePtr<CpuMatcher>(match_conf);
718
}
719
720
is_thread_safe_ = impl_->isThreadSafe();
721
num_matches_thresh1_ = num_matches_thresh1;
722
num_matches_thresh2_ = num_matches_thresh2;
723
}
724
725
726
void BestOf2NearestMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2,
727
MatchesInfo &matches_info)
728
{
729
CV_INSTRUMENT_REGION();
730
731
(*impl_)(features1, features2, matches_info);
732
733
// Check if it makes sense to find homography
734
if (matches_info.matches.size() < static_cast<size_t>(num_matches_thresh1_))
735
return;
736
737
// Construct point-point correspondences for homography estimation
738
Mat src_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);
739
Mat dst_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);
740
for (size_t i = 0; i < matches_info.matches.size(); ++i)
741
{
742
const DMatch& m = matches_info.matches[i];
743
744
Point2f p = features1.keypoints[m.queryIdx].pt;
745
p.x -= features1.img_size.width * 0.5f;
746
p.y -= features1.img_size.height * 0.5f;
747
src_points.at<Point2f>(0, static_cast<int>(i)) = p;
748
749
p = features2.keypoints[m.trainIdx].pt;
750
p.x -= features2.img_size.width * 0.5f;
751
p.y -= features2.img_size.height * 0.5f;
752
dst_points.at<Point2f>(0, static_cast<int>(i)) = p;
753
}
754
755
// Find pair-wise motion
756
matches_info.H = findHomography(src_points, dst_points, matches_info.inliers_mask, RANSAC);
757
if (matches_info.H.empty() || std::abs(determinant(matches_info.H)) < std::numeric_limits<double>::epsilon())
758
return;
759
760
// Find number of inliers
761
matches_info.num_inliers = 0;
762
for (size_t i = 0; i < matches_info.inliers_mask.size(); ++i)
763
if (matches_info.inliers_mask[i])
764
matches_info.num_inliers++;
765
766
// These coeffs are from paper M. Brown and D. Lowe. "Automatic Panoramic Image Stitching
767
// using Invariant Features"
768
matches_info.confidence = matches_info.num_inliers / (8 + 0.3 * matches_info.matches.size());
769
770
// Set zero confidence to remove matches between too close images, as they don't provide
771
// additional information anyway. The threshold was set experimentally.
772
matches_info.confidence = matches_info.confidence > 3. ? 0. : matches_info.confidence;
773
774
// Check if we should try to refine motion
775
if (matches_info.num_inliers < num_matches_thresh2_)
776
return;
777
778
// Construct point-point correspondences for inliers only
779
src_points.create(1, matches_info.num_inliers, CV_32FC2);
780
dst_points.create(1, matches_info.num_inliers, CV_32FC2);
781
int inlier_idx = 0;
782
for (size_t i = 0; i < matches_info.matches.size(); ++i)
783
{
784
if (!matches_info.inliers_mask[i])
785
continue;
786
787
const DMatch& m = matches_info.matches[i];
788
789
Point2f p = features1.keypoints[m.queryIdx].pt;
790
p.x -= features1.img_size.width * 0.5f;
791
p.y -= features1.img_size.height * 0.5f;
792
src_points.at<Point2f>(0, inlier_idx) = p;
793
794
p = features2.keypoints[m.trainIdx].pt;
795
p.x -= features2.img_size.width * 0.5f;
796
p.y -= features2.img_size.height * 0.5f;
797
dst_points.at<Point2f>(0, inlier_idx) = p;
798
799
inlier_idx++;
800
}
801
802
// Rerun motion estimation on inliers only
803
matches_info.H = findHomography(src_points, dst_points, RANSAC);
804
}
805
806
void BestOf2NearestMatcher::collectGarbage()
807
{
808
impl_->collectGarbage();
809
}
810
811
812
BestOf2NearestRangeMatcher::BestOf2NearestRangeMatcher(int range_width, bool try_use_gpu, float match_conf, int num_matches_thresh1, int num_matches_thresh2): BestOf2NearestMatcher(try_use_gpu, match_conf, num_matches_thresh1, num_matches_thresh2)
813
{
814
range_width_ = range_width;
815
}
816
817
818
void BestOf2NearestRangeMatcher::operator ()(const std::vector<ImageFeatures> &features, std::vector<MatchesInfo> &pairwise_matches,
819
const UMat &mask)
820
{
821
const int num_images = static_cast<int>(features.size());
822
823
CV_Assert(mask.empty() || (mask.type() == CV_8U && mask.cols == num_images && mask.rows));
824
Mat_<uchar> mask_(mask.getMat(ACCESS_READ));
825
if (mask_.empty())
826
mask_ = Mat::ones(num_images, num_images, CV_8U);
827
828
std::vector<std::pair<int,int> > near_pairs;
829
for (int i = 0; i < num_images - 1; ++i)
830
for (int j = i + 1; j < std::min(num_images, i + range_width_); ++j)
831
if (features[i].keypoints.size() > 0 && features[j].keypoints.size() > 0 && mask_(i, j))
832
near_pairs.push_back(std::make_pair(i, j));
833
834
pairwise_matches.resize(num_images * num_images);
835
MatchPairsBody body(*this, features, pairwise_matches, near_pairs);
836
837
if (is_thread_safe_)
838
parallel_for_(Range(0, static_cast<int>(near_pairs.size())), body);
839
else
840
body(Range(0, static_cast<int>(near_pairs.size())));
841
LOGLN_CHAT("");
842
}
843
844
845
void AffineBestOf2NearestMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2,
846
MatchesInfo &matches_info)
847
{
848
(*impl_)(features1, features2, matches_info);
849
850
// Check if it makes sense to find transform
851
if (matches_info.matches.size() < static_cast<size_t>(num_matches_thresh1_))
852
return;
853
854
// Construct point-point correspondences for transform estimation
855
Mat src_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);
856
Mat dst_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);
857
for (size_t i = 0; i < matches_info.matches.size(); ++i)
858
{
859
const cv::DMatch &m = matches_info.matches[i];
860
src_points.at<Point2f>(0, static_cast<int>(i)) = features1.keypoints[m.queryIdx].pt;
861
dst_points.at<Point2f>(0, static_cast<int>(i)) = features2.keypoints[m.trainIdx].pt;
862
}
863
864
// Find pair-wise motion
865
if (full_affine_)
866
matches_info.H = estimateAffine2D(src_points, dst_points, matches_info.inliers_mask);
867
else
868
matches_info.H = estimateAffinePartial2D(src_points, dst_points, matches_info.inliers_mask);
869
870
if (matches_info.H.empty()) {
871
// could not find transformation
872
matches_info.confidence = 0;
873
matches_info.num_inliers = 0;
874
return;
875
}
876
877
// Find number of inliers
878
matches_info.num_inliers = 0;
879
for (size_t i = 0; i < matches_info.inliers_mask.size(); ++i)
880
if (matches_info.inliers_mask[i])
881
matches_info.num_inliers++;
882
883
// These coeffs are from paper M. Brown and D. Lowe. "Automatic Panoramic
884
// Image Stitching using Invariant Features"
885
matches_info.confidence =
886
matches_info.num_inliers / (8 + 0.3 * matches_info.matches.size());
887
888
/* should we remove matches between too close images? */
889
// matches_info.confidence = matches_info.confidence > 3. ? 0. : matches_info.confidence;
890
891
// extend H to represent linear transformation in homogeneous coordinates
892
matches_info.H.push_back(Mat::zeros(1, 3, CV_64F));
893
matches_info.H.at<double>(2, 2) = 1;
894
}
895
896
897
} // namespace detail
898
} // namespace cv
899
900