I am trying to match images using SIFT keypoint detector and BRIEF descriptor. The matching is done using Flann LSHIndexParams. I give one image as input, and it is compared against 20 other images. To store the matched image, I use the drawMatch function. It works perfectly for a few of the images, but after a few iterations gives this error:
OpenCV Error: Assertion failed (i1 >= 0 && i1 < static_cast<int>(keypoints1.size ())) in drawMatches, file C:\OpenCV\opencv\modules\features2d\src\draw.cpp, line 207 terminate called after throwing an instance of 'cv::Exception' what(): C:\OpenCV\opencv\modules\features2d\src\draw.cpp:207: error: (-215) i1 >= 0 && i1 < static_cast<int>(keypoints1.size()) in function drawMatches
My code is as follows:
Mat imageSource= imread("1.jpg");
calculateSourceFeatures(imageC);
for(int i = 1; i <= NO_IMAGES; i++)
{
Mat image1 = imread(pathImage.arg(i).toStdString());
Mat image;
resize(image1, image, Size(256,256)/*new dimensions*/,0, 0, INTER_AREA/* interpolation method*/);
matchFeatures(imageSource, image,i );
}
void calculateSourceFeatures(Mat image)
{
cv::Ptr<FeatureDetector> featureDetector = cv::FeatureDetector::create("SIFT");
featureDetector->detect(image, keypoints);
cv::Ptr<DescriptorExtractor> featureExtractor = cv::DescriptorExtractor::create("BRIEF");
featureExtractor->compute(image, keypoints, descriptors);
}
void matchFeatures( Mat image, Mat target, int imageNo)
{
cv::Mat descriptors1;
std::vector<KeyPoint> keypoints1;
cv::Ptr<FeatureDetector> featureDetector = cv::FeatureDetector::create("SIFT");
cv::Ptr<DescriptorExtractor> featureExtractor = cv::DescriptorExtractor::create("BRIEF");
featureDetector->detect(target, keypoints1);
featureExtractor->compute(target, keypoints1, descriptors1);
cv::Ptr<cv::FlannBasedMatcher> matcher = new cv::FlannBasedMatcher(new cv::flann::LshIndexParams(5, 24, 2));
std::vector< DMatch > matches;
matcher->match( descriptors, descriptors1, matches );
double max_dist = 0; double min_dist = 100;
for( int i = 0; i < descriptors.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
std::vector< DMatch > good_matches;
for( int i = 0; i < descriptors.rows; i++ )
{
if( matches[i].distance <= 2*min_dist )
{
good_matches.push_back( matches[i]);
}
}
Mat img_matches;
drawMatches( image, keypoints, target, keypoints1,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
QString filename = "SIFTBRIEF_" + QString::number(imageNo) + ".jpg";
imwrite(filename.toStdString(), img_matches);
}