Path: blob/master/modules/stitching/src/matchers.cpp
16337 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.13// Copyright (C) 2009, Willow Garage Inc., all rights reserved.14// Third party copyrights are property of their respective owners.15//16// Redistribution and use in source and binary forms, with or without modification,17// are permitted provided that the following conditions are met:18//19// * Redistribution's of source code must retain the above copyright notice,20// this list of conditions and the following disclaimer.21//22// * Redistribution's in binary form must reproduce the above copyright notice,23// this list of conditions and the following disclaimer in the documentation24// and/or other materials provided with the distribution.25//26// * The name of the copyright holders may not be used to endorse or promote products27// derived from this software without specific prior written permission.28//29// This software is provided by the copyright holders and contributors "as is" and30// any express or implied warranties, including, but not limited to, the implied31// warranties of merchantability and fitness for a particular purpose are disclaimed.32// In no event shall the Intel Corporation or contributors be liable for any direct,33// indirect, incidental, special, exemplary, or consequential damages34// (including, but not limited to, procurement of substitute goods or services;35// loss of use, data, or profits; or business interruption) however caused36// and on any theory of liability, whether in contract, strict liability,37// or tort (including negligence or otherwise) arising in any way out of38// the use of this software, even if advised of the possibility of such damage.39//40//M*/4142#include "precomp.hpp"4344#include "opencv2/core/opencl/ocl_defs.hpp"4546using namespace cv;47using namespace cv::detail;48using namespace cv::cuda;4950#ifdef HAVE_OPENCV_XFEATURES2D51#include "opencv2/xfeatures2d.hpp"52using xfeatures2d::SURF;53using xfeatures2d::SIFT;54#else55# if defined(_MSC_VER)56# pragma warning(disable:4702) // unreachable code57# endif58#endif5960#ifdef HAVE_OPENCV_CUDAIMGPROC61# include "opencv2/cudaimgproc.hpp"62#endif6364namespace {6566struct DistIdxPair67{68bool operator<(const DistIdxPair &other) const { return dist < other.dist; }69double dist;70int idx;71};727374struct MatchPairsBody : ParallelLoopBody75{76MatchPairsBody(FeaturesMatcher &_matcher, const std::vector<ImageFeatures> &_features,77std::vector<MatchesInfo> &_pairwise_matches, std::vector<std::pair<int,int> > &_near_pairs)78: matcher(_matcher), features(_features),79pairwise_matches(_pairwise_matches), near_pairs(_near_pairs) {}8081void operator ()(const Range &r) const CV_OVERRIDE82{83cv::RNG rng = cv::theRNG(); // save entry rng state84const int num_images = static_cast<int>(features.size());85for (int i = r.start; i < r.end; ++i)86{87cv::theRNG() = cv::RNG(rng.state + i); // force "stable" RNG seed for each processed pair8889int from = near_pairs[i].first;90int to = near_pairs[i].second;91int pair_idx = from*num_images + to;9293matcher(features[from], features[to], pairwise_matches[pair_idx]);94pairwise_matches[pair_idx].src_img_idx = from;95pairwise_matches[pair_idx].dst_img_idx = to;9697size_t dual_pair_idx = to*num_images + from;9899pairwise_matches[dual_pair_idx] = pairwise_matches[pair_idx];100pairwise_matches[dual_pair_idx].src_img_idx = to;101pairwise_matches[dual_pair_idx].dst_img_idx = from;102103if (!pairwise_matches[pair_idx].H.empty())104pairwise_matches[dual_pair_idx].H = pairwise_matches[pair_idx].H.inv();105106for (size_t j = 0; j < pairwise_matches[dual_pair_idx].matches.size(); ++j)107std::swap(pairwise_matches[dual_pair_idx].matches[j].queryIdx,108pairwise_matches[dual_pair_idx].matches[j].trainIdx);109LOG(".");110}111}112113FeaturesMatcher &matcher;114const std::vector<ImageFeatures> &features;115std::vector<MatchesInfo> &pairwise_matches;116std::vector<std::pair<int,int> > &near_pairs;117118private:119void operator =(const MatchPairsBody&);120};121122123struct FindFeaturesBody : ParallelLoopBody124{125FindFeaturesBody(FeaturesFinder &finder, InputArrayOfArrays images,126std::vector<ImageFeatures> &features, const std::vector<std::vector<cv::Rect> > *rois)127: finder_(finder), images_(images), features_(features), rois_(rois) {}128129void operator ()(const Range &r) const CV_OVERRIDE130{131for (int i = r.start; i < r.end; ++i)132{133Mat image = images_.getMat(i);134if (rois_)135finder_(image, features_[i], (*rois_)[i]);136else137finder_(image, features_[i]);138}139}140141private:142FeaturesFinder &finder_;143InputArrayOfArrays images_;144std::vector<ImageFeatures> &features_;145const std::vector<std::vector<cv::Rect> > *rois_;146147// to cease visual studio warning148void operator =(const FindFeaturesBody&);149};150151152//////////////////////////////////////////////////////////////////////////////153154typedef std::set<std::pair<int,int> > MatchesSet;155156// These two classes are aimed to find features matches only, not to157// estimate homography158159class CpuMatcher CV_FINAL : public FeaturesMatcher160{161public:162CpuMatcher(float match_conf) : FeaturesMatcher(true), match_conf_(match_conf) {}163void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info) CV_OVERRIDE;164165private:166float match_conf_;167};168169#ifdef HAVE_OPENCV_CUDAFEATURES2D170class GpuMatcher CV_FINAL : public FeaturesMatcher171{172public:173GpuMatcher(float match_conf) : match_conf_(match_conf) {}174void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info);175176void collectGarbage();177178private:179float match_conf_;180GpuMat descriptors1_, descriptors2_;181GpuMat train_idx_, distance_, all_dist_;182std::vector< std::vector<DMatch> > pair_matches;183};184#endif185186187void CpuMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info)188{189CV_INSTRUMENT_REGION();190191CV_Assert(features1.descriptors.type() == features2.descriptors.type());192CV_Assert(features2.descriptors.depth() == CV_8U || features2.descriptors.depth() == CV_32F);193194matches_info.matches.clear();195196Ptr<cv::DescriptorMatcher> matcher;197#if 0 // TODO check this198if (ocl::isOpenCLActivated())199{200matcher = makePtr<BFMatcher>((int)NORM_L2);201}202else203#endif204{205Ptr<flann::IndexParams> indexParams = makePtr<flann::KDTreeIndexParams>();206Ptr<flann::SearchParams> searchParams = makePtr<flann::SearchParams>();207208if (features2.descriptors.depth() == CV_8U)209{210indexParams->setAlgorithm(cvflann::FLANN_INDEX_LSH);211searchParams->setAlgorithm(cvflann::FLANN_INDEX_LSH);212}213214matcher = makePtr<FlannBasedMatcher>(indexParams, searchParams);215}216std::vector< std::vector<DMatch> > pair_matches;217MatchesSet matches;218219// Find 1->2 matches220matcher->knnMatch(features1.descriptors, features2.descriptors, pair_matches, 2);221for (size_t i = 0; i < pair_matches.size(); ++i)222{223if (pair_matches[i].size() < 2)224continue;225const DMatch& m0 = pair_matches[i][0];226const DMatch& m1 = pair_matches[i][1];227if (m0.distance < (1.f - match_conf_) * m1.distance)228{229matches_info.matches.push_back(m0);230matches.insert(std::make_pair(m0.queryIdx, m0.trainIdx));231}232}233LOG("\n1->2 matches: " << matches_info.matches.size() << endl);234235// Find 2->1 matches236pair_matches.clear();237matcher->knnMatch(features2.descriptors, features1.descriptors, pair_matches, 2);238for (size_t i = 0; i < pair_matches.size(); ++i)239{240if (pair_matches[i].size() < 2)241continue;242const DMatch& m0 = pair_matches[i][0];243const DMatch& m1 = pair_matches[i][1];244if (m0.distance < (1.f - match_conf_) * m1.distance)245if (matches.find(std::make_pair(m0.trainIdx, m0.queryIdx)) == matches.end())246matches_info.matches.push_back(DMatch(m0.trainIdx, m0.queryIdx, m0.distance));247}248LOG("1->2 & 2->1 matches: " << matches_info.matches.size() << endl);249}250251#ifdef HAVE_OPENCV_CUDAFEATURES2D252void GpuMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo& matches_info)253{254CV_INSTRUMENT_REGION();255256matches_info.matches.clear();257258ensureSizeIsEnough(features1.descriptors.size(), features1.descriptors.type(), descriptors1_);259ensureSizeIsEnough(features2.descriptors.size(), features2.descriptors.type(), descriptors2_);260261descriptors1_.upload(features1.descriptors);262descriptors2_.upload(features2.descriptors);263264//TODO: NORM_L1 allows to avoid matcher crashes for ORB features, but is not absolutely correct for them.265// The best choice for ORB features is NORM_HAMMING, but it is incorrect for SURF features.266// More accurate fix in this place should be done in the future -- the type of the norm267// should be either a parameter of this method, or a field of the class.268Ptr<cuda::DescriptorMatcher> matcher = cuda::DescriptorMatcher::createBFMatcher(NORM_L1);269270MatchesSet matches;271272// Find 1->2 matches273pair_matches.clear();274matcher->knnMatch(descriptors1_, descriptors2_, pair_matches, 2);275for (size_t i = 0; i < pair_matches.size(); ++i)276{277if (pair_matches[i].size() < 2)278continue;279const DMatch& m0 = pair_matches[i][0];280const DMatch& m1 = pair_matches[i][1];281if (m0.distance < (1.f - match_conf_) * m1.distance)282{283matches_info.matches.push_back(m0);284matches.insert(std::make_pair(m0.queryIdx, m0.trainIdx));285}286}287288// Find 2->1 matches289pair_matches.clear();290matcher->knnMatch(descriptors2_, descriptors1_, pair_matches, 2);291for (size_t i = 0; i < pair_matches.size(); ++i)292{293if (pair_matches[i].size() < 2)294continue;295const DMatch& m0 = pair_matches[i][0];296const DMatch& m1 = pair_matches[i][1];297if (m0.distance < (1.f - match_conf_) * m1.distance)298if (matches.find(std::make_pair(m0.trainIdx, m0.queryIdx)) == matches.end())299matches_info.matches.push_back(DMatch(m0.trainIdx, m0.queryIdx, m0.distance));300}301}302303void GpuMatcher::collectGarbage()304{305descriptors1_.release();306descriptors2_.release();307train_idx_.release();308distance_.release();309all_dist_.release();310std::vector< std::vector<DMatch> >().swap(pair_matches);311}312#endif313314} // namespace315316317namespace cv {318namespace detail {319320void FeaturesFinder::operator ()(InputArray image, ImageFeatures &features)321{322find(image, features);323features.img_size = image.size();324}325326327void FeaturesFinder::operator ()(InputArray image, ImageFeatures &features, const std::vector<Rect> &rois)328{329std::vector<ImageFeatures> roi_features(rois.size());330size_t total_kps_count = 0;331int total_descriptors_height = 0;332333for (size_t i = 0; i < rois.size(); ++i)334{335find(image.getUMat()(rois[i]), roi_features[i]);336total_kps_count += roi_features[i].keypoints.size();337total_descriptors_height += roi_features[i].descriptors.rows;338}339340features.img_size = image.size();341features.keypoints.resize(total_kps_count);342features.descriptors.create(total_descriptors_height,343roi_features[0].descriptors.cols,344roi_features[0].descriptors.type());345346int kp_idx = 0;347int descr_offset = 0;348for (size_t i = 0; i < rois.size(); ++i)349{350for (size_t j = 0; j < roi_features[i].keypoints.size(); ++j, ++kp_idx)351{352features.keypoints[kp_idx] = roi_features[i].keypoints[j];353features.keypoints[kp_idx].pt.x += (float)rois[i].x;354features.keypoints[kp_idx].pt.y += (float)rois[i].y;355}356UMat subdescr = features.descriptors.rowRange(357descr_offset, descr_offset + roi_features[i].descriptors.rows);358roi_features[i].descriptors.copyTo(subdescr);359descr_offset += roi_features[i].descriptors.rows;360}361}362363364void FeaturesFinder::operator ()(InputArrayOfArrays images, std::vector<ImageFeatures> &features)365{366size_t count = images.total();367features.resize(count);368369FindFeaturesBody body(*this, images, features, NULL);370if (isThreadSafe())371parallel_for_(Range(0, static_cast<int>(count)), body);372else373body(Range(0, static_cast<int>(count)));374}375376377void FeaturesFinder::operator ()(InputArrayOfArrays images, std::vector<ImageFeatures> &features,378const std::vector<std::vector<cv::Rect> > &rois)379{380CV_Assert(rois.size() == images.total());381size_t count = images.total();382features.resize(count);383384FindFeaturesBody body(*this, images, features, &rois);385if (isThreadSafe())386parallel_for_(Range(0, static_cast<int>(count)), body);387else388body(Range(0, static_cast<int>(count)));389}390391392bool FeaturesFinder::isThreadSafe() const393{394#ifdef HAVE_OPENCL395if (ocl::isOpenCLActivated())396{397return false;398}399#endif400if (dynamic_cast<const SurfFeaturesFinder*>(this))401{402return true;403}404else if (dynamic_cast<const OrbFeaturesFinder*>(this))405{406return true;407}408else409{410return false;411}412}413414415SurfFeaturesFinder::SurfFeaturesFinder(double hess_thresh, int num_octaves, int num_layers,416int num_octaves_descr, int num_layers_descr)417{418#ifdef HAVE_OPENCV_XFEATURES2D419if (num_octaves_descr == num_octaves && num_layers_descr == num_layers)420{421Ptr<SURF> surf_ = SURF::create();422if( !surf_ )423CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" );424surf_->setHessianThreshold(hess_thresh);425surf_->setNOctaves(num_octaves);426surf_->setNOctaveLayers(num_layers);427surf = surf_;428}429else430{431Ptr<SURF> sdetector_ = SURF::create();432Ptr<SURF> sextractor_ = SURF::create();433434if( !sdetector_ || !sextractor_ )435CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" );436437sdetector_->setHessianThreshold(hess_thresh);438sdetector_->setNOctaves(num_octaves);439sdetector_->setNOctaveLayers(num_layers);440441sextractor_->setNOctaves(num_octaves_descr);442sextractor_->setNOctaveLayers(num_layers_descr);443444detector_ = sdetector_;445extractor_ = sextractor_;446}447#else448CV_UNUSED(hess_thresh);449CV_UNUSED(num_octaves);450CV_UNUSED(num_layers);451CV_UNUSED(num_octaves_descr);452CV_UNUSED(num_layers_descr);453CV_Error( Error::StsNotImplemented, "OpenCV was built without SURF support" );454#endif455}456457void SurfFeaturesFinder::find(InputArray image, ImageFeatures &features)458{459UMat gray_image;460CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC1));461if(image.type() == CV_8UC3)462{463cvtColor(image, gray_image, COLOR_BGR2GRAY);464}465else466{467gray_image = image.getUMat();468}469if (!surf)470{471detector_->detect(gray_image, features.keypoints);472extractor_->compute(gray_image, features.keypoints, features.descriptors);473}474else475{476UMat descriptors;477surf->detectAndCompute(gray_image, Mat(), features.keypoints, descriptors);478features.descriptors = descriptors.reshape(1, (int)features.keypoints.size());479}480}481482SiftFeaturesFinder::SiftFeaturesFinder()483{484#ifdef HAVE_OPENCV_XFEATURES2D485Ptr<SIFT> sift_ = SIFT::create();486if( !sift_ )487CV_Error( Error::StsNotImplemented, "OpenCV was built without SIFT support" );488sift = sift_;489#else490CV_Error( Error::StsNotImplemented, "OpenCV was built without SIFT support" );491#endif492}493494void SiftFeaturesFinder::find(InputArray image, ImageFeatures &features)495{496UMat gray_image;497CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC1));498if(image.type() == CV_8UC3)499{500cvtColor(image, gray_image, COLOR_BGR2GRAY);501}502else503{504gray_image = image.getUMat();505}506UMat descriptors;507sift->detectAndCompute(gray_image, Mat(), features.keypoints, descriptors);508features.descriptors = descriptors.reshape(1, (int)features.keypoints.size());509}510511OrbFeaturesFinder::OrbFeaturesFinder(Size _grid_size, int n_features, float scaleFactor, int nlevels)512{513grid_size = _grid_size;514orb = ORB::create(n_features * (99 + grid_size.area())/100/grid_size.area(), scaleFactor, nlevels);515}516517void OrbFeaturesFinder::find(InputArray image, ImageFeatures &features)518{519UMat gray_image;520521CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC4) || (image.type() == CV_8UC1));522523if (image.type() == CV_8UC3) {524cvtColor(image, gray_image, COLOR_BGR2GRAY);525} else if (image.type() == CV_8UC4) {526cvtColor(image, gray_image, COLOR_BGRA2GRAY);527} else if (image.type() == CV_8UC1) {528gray_image = image.getUMat();529} else {530CV_Error(Error::StsUnsupportedFormat, "");531}532533if (grid_size.area() == 1)534orb->detectAndCompute(gray_image, Mat(), features.keypoints, features.descriptors);535else536{537features.keypoints.clear();538features.descriptors.release();539540std::vector<KeyPoint> points;541Mat _descriptors;542UMat descriptors;543544for (int r = 0; r < grid_size.height; ++r)545for (int c = 0; c < grid_size.width; ++c)546{547int xl = c * gray_image.cols / grid_size.width;548int yl = r * gray_image.rows / grid_size.height;549int xr = (c+1) * gray_image.cols / grid_size.width;550int yr = (r+1) * gray_image.rows / grid_size.height;551552// LOGLN("OrbFeaturesFinder::find: gray_image.empty=" << (gray_image.empty()?"true":"false") << ", "553// << " gray_image.size()=(" << gray_image.size().width << "x" << gray_image.size().height << "), "554// << " yl=" << yl << ", yr=" << yr << ", "555// << " xl=" << xl << ", xr=" << xr << ", gray_image.data=" << ((size_t)gray_image.data) << ", "556// << "gray_image.dims=" << gray_image.dims << "\n");557558UMat gray_image_part=gray_image(Range(yl, yr), Range(xl, xr));559// LOGLN("OrbFeaturesFinder::find: gray_image_part.empty=" << (gray_image_part.empty()?"true":"false") << ", "560// << " gray_image_part.size()=(" << gray_image_part.size().width << "x" << gray_image_part.size().height << "), "561// << " gray_image_part.dims=" << gray_image_part.dims << ", "562// << " gray_image_part.data=" << ((size_t)gray_image_part.data) << "\n");563564orb->detectAndCompute(gray_image_part, UMat(), points, descriptors);565566features.keypoints.reserve(features.keypoints.size() + points.size());567for (std::vector<KeyPoint>::iterator kp = points.begin(); kp != points.end(); ++kp)568{569kp->pt.x += xl;570kp->pt.y += yl;571features.keypoints.push_back(*kp);572}573_descriptors.push_back(descriptors.getMat(ACCESS_READ));574}575576// TODO optimize copyTo()577//features.descriptors = _descriptors.getUMat(ACCESS_READ);578_descriptors.copyTo(features.descriptors);579}580}581582AKAZEFeaturesFinder::AKAZEFeaturesFinder(AKAZE::DescriptorType descriptor_type,583int descriptor_size,584int descriptor_channels,585float threshold,586int nOctaves,587int nOctaveLayers,588KAZE::DiffusivityType diffusivity)589{590akaze = AKAZE::create(descriptor_type, descriptor_size, descriptor_channels,591threshold, nOctaves, nOctaveLayers, diffusivity);592}593594void AKAZEFeaturesFinder::find(InputArray image, detail::ImageFeatures &features)595{596CV_Assert((image.type() == CV_8UC3) || (image.type() == CV_8UC1));597akaze->detectAndCompute(image, noArray(), features.keypoints, features.descriptors);598}599600#ifdef HAVE_OPENCV_XFEATURES2D601SurfFeaturesFinderGpu::SurfFeaturesFinderGpu(double hess_thresh, int num_octaves, int num_layers,602int num_octaves_descr, int num_layers_descr)603{604surf_.keypointsRatio = 0.1f;605surf_.hessianThreshold = hess_thresh;606surf_.extended = false;607num_octaves_ = num_octaves;608num_layers_ = num_layers;609num_octaves_descr_ = num_octaves_descr;610num_layers_descr_ = num_layers_descr;611}612613614void SurfFeaturesFinderGpu::find(InputArray image, ImageFeatures &features)615{616CV_Assert(image.depth() == CV_8U);617618ensureSizeIsEnough(image.size(), image.type(), image_);619image_.upload(image);620621ensureSizeIsEnough(image.size(), CV_8UC1, gray_image_);622623#ifdef HAVE_OPENCV_CUDAIMGPROC624cv::cuda::cvtColor(image_, gray_image_, COLOR_BGR2GRAY);625#else626cvtColor(image_, gray_image_, COLOR_BGR2GRAY);627#endif628629surf_.nOctaves = num_octaves_;630surf_.nOctaveLayers = num_layers_;631surf_.upright = false;632surf_(gray_image_, GpuMat(), keypoints_);633634surf_.nOctaves = num_octaves_descr_;635surf_.nOctaveLayers = num_layers_descr_;636surf_.upright = true;637surf_(gray_image_, GpuMat(), keypoints_, descriptors_, true);638surf_.downloadKeypoints(keypoints_, features.keypoints);639640descriptors_.download(features.descriptors);641}642643void SurfFeaturesFinderGpu::collectGarbage()644{645surf_.releaseMemory();646image_.release();647gray_image_.release();648keypoints_.release();649descriptors_.release();650}651#endif652653654//////////////////////////////////////////////////////////////////////////////655656MatchesInfo::MatchesInfo() : src_img_idx(-1), dst_img_idx(-1), num_inliers(0), confidence(0) {}657658MatchesInfo::MatchesInfo(const MatchesInfo &other) { *this = other; }659660MatchesInfo& MatchesInfo::operator =(const MatchesInfo &other)661{662src_img_idx = other.src_img_idx;663dst_img_idx = other.dst_img_idx;664matches = other.matches;665inliers_mask = other.inliers_mask;666num_inliers = other.num_inliers;667H = other.H.clone();668confidence = other.confidence;669return *this;670}671672673//////////////////////////////////////////////////////////////////////////////674675void FeaturesMatcher::operator ()(const std::vector<ImageFeatures> &features, std::vector<MatchesInfo> &pairwise_matches,676const UMat &mask)677{678const int num_images = static_cast<int>(features.size());679680CV_Assert(mask.empty() || (mask.type() == CV_8U && mask.cols == num_images && mask.rows));681Mat_<uchar> mask_(mask.getMat(ACCESS_READ));682if (mask_.empty())683mask_ = Mat::ones(num_images, num_images, CV_8U);684685std::vector<std::pair<int,int> > near_pairs;686for (int i = 0; i < num_images - 1; ++i)687for (int j = i + 1; j < num_images; ++j)688if (features[i].keypoints.size() > 0 && features[j].keypoints.size() > 0 && mask_(i, j))689near_pairs.push_back(std::make_pair(i, j));690691pairwise_matches.resize(num_images * num_images);692MatchPairsBody body(*this, features, pairwise_matches, near_pairs);693694if (is_thread_safe_)695parallel_for_(Range(0, static_cast<int>(near_pairs.size())), body);696else697body(Range(0, static_cast<int>(near_pairs.size())));698LOGLN_CHAT("");699}700701702//////////////////////////////////////////////////////////////////////////////703704BestOf2NearestMatcher::BestOf2NearestMatcher(bool try_use_gpu, float match_conf, int num_matches_thresh1, int num_matches_thresh2)705{706CV_UNUSED(try_use_gpu);707708#ifdef HAVE_OPENCV_CUDAFEATURES2D709if (try_use_gpu && getCudaEnabledDeviceCount() > 0)710{711impl_ = makePtr<GpuMatcher>(match_conf);712}713else714#endif715{716impl_ = makePtr<CpuMatcher>(match_conf);717}718719is_thread_safe_ = impl_->isThreadSafe();720num_matches_thresh1_ = num_matches_thresh1;721num_matches_thresh2_ = num_matches_thresh2;722}723724725void BestOf2NearestMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2,726MatchesInfo &matches_info)727{728CV_INSTRUMENT_REGION();729730(*impl_)(features1, features2, matches_info);731732// Check if it makes sense to find homography733if (matches_info.matches.size() < static_cast<size_t>(num_matches_thresh1_))734return;735736// Construct point-point correspondences for homography estimation737Mat src_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);738Mat dst_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);739for (size_t i = 0; i < matches_info.matches.size(); ++i)740{741const DMatch& m = matches_info.matches[i];742743Point2f p = features1.keypoints[m.queryIdx].pt;744p.x -= features1.img_size.width * 0.5f;745p.y -= features1.img_size.height * 0.5f;746src_points.at<Point2f>(0, static_cast<int>(i)) = p;747748p = features2.keypoints[m.trainIdx].pt;749p.x -= features2.img_size.width * 0.5f;750p.y -= features2.img_size.height * 0.5f;751dst_points.at<Point2f>(0, static_cast<int>(i)) = p;752}753754// Find pair-wise motion755matches_info.H = findHomography(src_points, dst_points, matches_info.inliers_mask, RANSAC);756if (matches_info.H.empty() || std::abs(determinant(matches_info.H)) < std::numeric_limits<double>::epsilon())757return;758759// Find number of inliers760matches_info.num_inliers = 0;761for (size_t i = 0; i < matches_info.inliers_mask.size(); ++i)762if (matches_info.inliers_mask[i])763matches_info.num_inliers++;764765// These coeffs are from paper M. Brown and D. Lowe. "Automatic Panoramic Image Stitching766// using Invariant Features"767matches_info.confidence = matches_info.num_inliers / (8 + 0.3 * matches_info.matches.size());768769// Set zero confidence to remove matches between too close images, as they don't provide770// additional information anyway. The threshold was set experimentally.771matches_info.confidence = matches_info.confidence > 3. ? 0. : matches_info.confidence;772773// Check if we should try to refine motion774if (matches_info.num_inliers < num_matches_thresh2_)775return;776777// Construct point-point correspondences for inliers only778src_points.create(1, matches_info.num_inliers, CV_32FC2);779dst_points.create(1, matches_info.num_inliers, CV_32FC2);780int inlier_idx = 0;781for (size_t i = 0; i < matches_info.matches.size(); ++i)782{783if (!matches_info.inliers_mask[i])784continue;785786const DMatch& m = matches_info.matches[i];787788Point2f p = features1.keypoints[m.queryIdx].pt;789p.x -= features1.img_size.width * 0.5f;790p.y -= features1.img_size.height * 0.5f;791src_points.at<Point2f>(0, inlier_idx) = p;792793p = features2.keypoints[m.trainIdx].pt;794p.x -= features2.img_size.width * 0.5f;795p.y -= features2.img_size.height * 0.5f;796dst_points.at<Point2f>(0, inlier_idx) = p;797798inlier_idx++;799}800801// Rerun motion estimation on inliers only802matches_info.H = findHomography(src_points, dst_points, RANSAC);803}804805void BestOf2NearestMatcher::collectGarbage()806{807impl_->collectGarbage();808}809810811BestOf2NearestRangeMatcher::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)812{813range_width_ = range_width;814}815816817void BestOf2NearestRangeMatcher::operator ()(const std::vector<ImageFeatures> &features, std::vector<MatchesInfo> &pairwise_matches,818const UMat &mask)819{820const int num_images = static_cast<int>(features.size());821822CV_Assert(mask.empty() || (mask.type() == CV_8U && mask.cols == num_images && mask.rows));823Mat_<uchar> mask_(mask.getMat(ACCESS_READ));824if (mask_.empty())825mask_ = Mat::ones(num_images, num_images, CV_8U);826827std::vector<std::pair<int,int> > near_pairs;828for (int i = 0; i < num_images - 1; ++i)829for (int j = i + 1; j < std::min(num_images, i + range_width_); ++j)830if (features[i].keypoints.size() > 0 && features[j].keypoints.size() > 0 && mask_(i, j))831near_pairs.push_back(std::make_pair(i, j));832833pairwise_matches.resize(num_images * num_images);834MatchPairsBody body(*this, features, pairwise_matches, near_pairs);835836if (is_thread_safe_)837parallel_for_(Range(0, static_cast<int>(near_pairs.size())), body);838else839body(Range(0, static_cast<int>(near_pairs.size())));840LOGLN_CHAT("");841}842843844void AffineBestOf2NearestMatcher::match(const ImageFeatures &features1, const ImageFeatures &features2,845MatchesInfo &matches_info)846{847(*impl_)(features1, features2, matches_info);848849// Check if it makes sense to find transform850if (matches_info.matches.size() < static_cast<size_t>(num_matches_thresh1_))851return;852853// Construct point-point correspondences for transform estimation854Mat src_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);855Mat dst_points(1, static_cast<int>(matches_info.matches.size()), CV_32FC2);856for (size_t i = 0; i < matches_info.matches.size(); ++i)857{858const cv::DMatch &m = matches_info.matches[i];859src_points.at<Point2f>(0, static_cast<int>(i)) = features1.keypoints[m.queryIdx].pt;860dst_points.at<Point2f>(0, static_cast<int>(i)) = features2.keypoints[m.trainIdx].pt;861}862863// Find pair-wise motion864if (full_affine_)865matches_info.H = estimateAffine2D(src_points, dst_points, matches_info.inliers_mask);866else867matches_info.H = estimateAffinePartial2D(src_points, dst_points, matches_info.inliers_mask);868869if (matches_info.H.empty()) {870// could not find transformation871matches_info.confidence = 0;872matches_info.num_inliers = 0;873return;874}875876// Find number of inliers877matches_info.num_inliers = 0;878for (size_t i = 0; i < matches_info.inliers_mask.size(); ++i)879if (matches_info.inliers_mask[i])880matches_info.num_inliers++;881882// These coeffs are from paper M. Brown and D. Lowe. "Automatic Panoramic883// Image Stitching using Invariant Features"884matches_info.confidence =885matches_info.num_inliers / (8 + 0.3 * matches_info.matches.size());886887/* should we remove matches between too close images? */888// matches_info.confidence = matches_info.confidence > 3. ? 0. : matches_info.confidence;889890// extend H to represent linear transformation in homogeneous coordinates891matches_info.H.push_back(Mat::zeros(1, 3, CV_64F));892matches_info.H.at<double>(2, 2) = 1;893}894895896} // namespace detail897} // namespace cv898899900