opencv/modules/features2d/src/keypoint.cpp

267 lines
8.6 KiB
C++
Raw Normal View History

/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2008, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
namespace cv
{
2011-05-31 22:24:45 +08:00
struct KeypointResponseGreaterThanThreshold
{
KeypointResponseGreaterThanThreshold(float _value) :
value(_value)
{
}
inline bool operator()(const KeyPoint& kpt) const
{
return kpt.response >= value;
}
float value;
};
struct KeypointResponseGreater
{
inline bool operator()(const KeyPoint& kp1, const KeyPoint& kp2) const
{
return kp1.response > kp2.response;
}
};
// takes keypoints and culls them by the response
void KeyPointsFilter::retainBest(std::vector<KeyPoint>& keypoints, int n_points)
{
//this is only necessary if the keypoints size is greater than the number of desired points.
if( n_points >= 0 && keypoints.size() > (size_t)n_points )
{
if (n_points==0)
{
keypoints.clear();
return;
}
//first use nth element to partition the keypoints into the best and worst.
std::nth_element(keypoints.begin(), keypoints.begin() + n_points, keypoints.end(), KeypointResponseGreater());
//this is the boundary response, and in the case of FAST may be ambiguous
float ambiguous_response = keypoints[n_points - 1].response;
//use std::partition to grab all of the keypoints with the boundary response.
std::vector<KeyPoint>::const_iterator new_end =
std::partition(keypoints.begin() + n_points, keypoints.end(),
KeypointResponseGreaterThanThreshold(ambiguous_response));
//resize the keypoints, given this new end point. nth_element and partition reordered the points inplace
keypoints.resize(new_end - keypoints.begin());
}
}
struct RoiPredicate
{
RoiPredicate( const Rect& _r ) : r(_r)
{}
bool operator()( const KeyPoint& keyPt ) const
{
return !r.contains( keyPt.pt );
}
Rect r;
};
void KeyPointsFilter::runByImageBorder( std::vector<KeyPoint>& keypoints, Size imageSize, int borderSize )
{
if( borderSize > 0)
{
if (imageSize.height <= borderSize * 2 || imageSize.width <= borderSize * 2)
keypoints.clear();
else
2012-12-21 23:58:51 +08:00
keypoints.erase( std::remove_if(keypoints.begin(), keypoints.end(),
RoiPredicate(Rect(Point(borderSize, borderSize),
Point(imageSize.width - borderSize, imageSize.height - borderSize)))),
keypoints.end() );
}
}
struct SizePredicate
{
SizePredicate( float _minSize, float _maxSize ) : minSize(_minSize), maxSize(_maxSize)
{}
bool operator()( const KeyPoint& keyPt ) const
{
float size = keyPt.size;
return (size < minSize) || (size > maxSize);
}
float minSize, maxSize;
};
void KeyPointsFilter::runByKeypointSize( std::vector<KeyPoint>& keypoints, float minSize, float maxSize )
{
CV_Assert( minSize >= 0 );
CV_Assert( maxSize >= 0);
CV_Assert( minSize <= maxSize );
2012-12-21 23:58:51 +08:00
keypoints.erase( std::remove_if(keypoints.begin(), keypoints.end(), SizePredicate(minSize, maxSize)),
keypoints.end() );
}
2011-05-05 18:10:46 +08:00
class MaskPredicate
{
public:
MaskPredicate( const Mat& _mask ) : mask(_mask) {}
bool operator() (const KeyPoint& key_pt) const
{
return mask.at<uchar>( (int)(key_pt.pt.y + 0.5f), (int)(key_pt.pt.x + 0.5f) ) == 0;
}
private:
const Mat mask;
MaskPredicate& operator=(const MaskPredicate&);
2011-05-05 18:10:46 +08:00
};
void KeyPointsFilter::runByPixelsMask( std::vector<KeyPoint>& keypoints, const Mat& mask )
2011-05-05 18:10:46 +08:00
{
CV_INSTRUMENT_REGION();
Merge pull request #8951 from hrnr:akaze_part2 [GSOC] Speeding-up AKAZE, part #2 (#8951) * feature2d: instrument more functions used in AKAZE * rework Compute_Determinant_Hessian_Response * this takes 84% of time of Feature_Detection * run everything in parallel * compute Scharr kernels just once * compute sigma more efficiently * allocate all matrices in evolution without zeroing * features2d: add one bigger image to tests * now test have images: 600x768, 900x600 and 1385x700 to cover different resolutions * explicitly zero Lx and Ly * add Lflow and Lstep to evolution as in original AKAZE code * reworked computing keypoints orientation integrated faster function from https://github.com/h2suzuki/fast_akaze * use standard fastAtan2 instead of getAngle * compute keypoints orientation in parallel * fix visual studio warnings * replace some wrapped functions with direct calls to OpenCV functions * improved readability for people familiar with opencv * do not same image twice in base level * rework diffusity stencil * use one pass stencil for diffusity from https://github.com/h2suzuki/fast_akaze * improve locality in Create_Scale_Space * always compute determinat od hessian and spacial derivatives * this needs to be computed always as we need derivatives while computing descriptors * fixed tests of AKAZE with KAZE descriptors which have been affected by this Currently it computes all first and second order derivatives together and the determiant of the hessian. For descriptors it would be enough to compute just first order derivates, but it is not probably worth it optimize for scenario where descriptors and keypoints are computed separately, since it is already very inefficient. When computing keypoint and descriptors together it is faster to do it the current way (preserves locality). * parallelize non linear diffusion computation * do multiplication right in the nlp diffusity kernel * rework kfactor computation * get rid of sharing buffers when creating scale space pyramid, the performace impact is neglegible * features2d: initialize TBB scheduler in perf tests * ensures more stable output * more reasonable profiles, since the first call of parallel_for_ is not getting big performace hit * compute_kfactor: interleave finding of maximum and computing distance * no need to go twice through the data * start to use UMats in AKAZE to leverage OpenCl in the future * fixed bug that prevented computing determinant for scale pyramid of size 1 (just the base image) * all descriptors now support writing to uninitialized memory * use InputArray and OutputArray for input image and descriptors, allows to make use UMAt that user passes to us * enable use of all existing ocl paths in AKAZE * all parts that uses ocl-enabled functions should use ocl by now * imgproc: fix dispatching of IPP version when OCL is disabled * when OCL is disabled IPP version should be always prefered (even when the dst is UMat) * get rid of copy in DeterminantHessian response * this slows CPU version considerably * do no run in parallel when running with OCL * store derivations as UMat in pyramid * enables OCL path computing of determint hessian * will allow to compute descriptors on GPU in the future * port diffusivity to OCL * diffusivity itself is not a blocker, but this saves us downloading and uploading derivations * implement kernel for nonlinear scalar diffusion step * download the pyramid from GPU just once we don't want to downlaod matrices ad hoc from gpu when the function in AKAZE needs it. There is a HUGE mapping overhead and without shared memory support a LOT of unnecessary transfers. This maps/downloads matrices just once. * fix bug with uninitialized values in non linear diffusion * this was causing spurious segfaults in stitching tests due to propagation of NaNs * added new test, which checks for NaNs (added new debug asserts for NaNs) * valgrind now says everything is ok * add nonlinear diffusion step OCL implementation * Lt in pyramid changed to UMat, it will be downlaoded from GPU along with Lx, Ly * fix bug in pm_g2 kernel. OpenCV mangles dimensions passed to OpenCL, so we need to check for boundaries in each OCL kernel. * port computing of determinant to OCL * computing of determinant is not a blocker, but with this change we don't need to download all spatial derivatives to CPU, we only download determinant * make Ldet in the pyramid UMat, download it from CPU together with the other parts of the pyramid * add profiling macros * fix visual studio warning * instrument non_linear_diffusion * remove changes I have made to TEvolution * TEvolution is used only in KAZE now * Revert "features2d: initialize TBB scheduler in perf tests" This reverts commit ba81e2a711ae009ce3c5459775627b6423112669.
2017-08-01 20:46:01 +08:00
2011-05-05 18:10:46 +08:00
if( mask.empty() )
return;
2012-12-21 23:58:51 +08:00
keypoints.erase(std::remove_if(keypoints.begin(), keypoints.end(), MaskPredicate(mask)), keypoints.end());
2011-05-05 18:10:46 +08:00
}
struct KeyPoint_LessThan
{
KeyPoint_LessThan(const std::vector<KeyPoint>& _kp) : kp(&_kp) {}
bool operator()(int i, int j) const
{
const KeyPoint& kp1 = (*kp)[i];
const KeyPoint& kp2 = (*kp)[j];
if( kp1.pt.x != kp2.pt.x )
return kp1.pt.x < kp2.pt.x;
if( kp1.pt.y != kp2.pt.y )
return kp1.pt.y < kp2.pt.y;
if( kp1.size != kp2.size )
return kp1.size > kp2.size;
if( kp1.angle != kp2.angle )
return kp1.angle < kp2.angle;
if( kp1.response != kp2.response )
return kp1.response > kp2.response;
if( kp1.octave != kp2.octave )
return kp1.octave > kp2.octave;
if( kp1.class_id != kp2.class_id )
return kp1.class_id > kp2.class_id;
return i < j;
}
const std::vector<KeyPoint>* kp;
};
void KeyPointsFilter::removeDuplicated( std::vector<KeyPoint>& keypoints )
{
int i, j, n = (int)keypoints.size();
std::vector<int> kpidx(n);
std::vector<uchar> mask(n, (uchar)1);
for( i = 0; i < n; i++ )
kpidx[i] = i;
std::sort(kpidx.begin(), kpidx.end(), KeyPoint_LessThan(keypoints));
for( i = 1, j = 0; i < n; i++ )
{
KeyPoint& kp1 = keypoints[kpidx[i]];
KeyPoint& kp2 = keypoints[kpidx[j]];
if( kp1.pt.x != kp2.pt.x || kp1.pt.y != kp2.pt.y ||
kp1.size != kp2.size || kp1.angle != kp2.angle )
j = i;
else
mask[kpidx[i]] = 0;
}
for( i = j = 0; i < n; i++ )
{
if( mask[i] )
{
if( i != j )
keypoints[j] = keypoints[i];
j++;
}
}
keypoints.resize(j);
}
struct KeyPoint12_LessThan
{
bool operator()(const KeyPoint &kp1, const KeyPoint &kp2) const
{
if( kp1.pt.x != kp2.pt.x )
return kp1.pt.x < kp2.pt.x;
if( kp1.pt.y != kp2.pt.y )
return kp1.pt.y < kp2.pt.y;
if( kp1.size != kp2.size )
return kp1.size > kp2.size;
if( kp1.angle != kp2.angle )
return kp1.angle < kp2.angle;
if( kp1.response != kp2.response )
return kp1.response > kp2.response;
if( kp1.octave != kp2.octave )
return kp1.octave > kp2.octave;
return kp1.class_id > kp2.class_id;
}
};
void KeyPointsFilter::removeDuplicatedSorted( std::vector<KeyPoint>& keypoints )
{
int i, j, n = (int)keypoints.size();
if (n < 2) return;
std::sort(keypoints.begin(), keypoints.end(), KeyPoint12_LessThan());
for( i = 0, j = 1; j < n; ++j )
{
const KeyPoint& kp1 = keypoints[i];
const KeyPoint& kp2 = keypoints[j];
if( kp1.pt.x != kp2.pt.x || kp1.pt.y != kp2.pt.y ||
kp1.size != kp2.size || kp1.angle != kp2.angle ) {
keypoints[++i] = keypoints[j];
}
}
keypoints.resize(i + 1);
}
}