2 * A Demo to OpenCV Implementation of SURF
3 * Further Information Refer to "SURF: Speed-Up Robust Feature"
5 * liuliu.1987+opencv@gmail.com
7 #include <opencv2/core/core.hpp>
8 #include <opencv2/objdetect/objdetect.hpp>
9 #include <opencv2/features2d/features2d.hpp>
10 #include <opencv2/highgui/highgui.hpp>
11 #include <opencv2/calib3d/calib3d.hpp>
12 #include <opencv2/imgproc/imgproc_c.h>
22 printf( "This program demonstrated the use of the SURF Detector and Descriptor using\n"
23 "either FLANN (fast approx nearst neighbor classification) or brute force matching\n"
24 "on planar objects.\n"
26 "./find_obj [--object_filename]=<object_filename, box.png as default> \n"
27 "[--scene_filename]=<scene_filename box_in_scene.png as default>]\n\n"
31 // define whether to use approximate nearest-neighbor search
38 compareSURFDescriptors( const float* d1, const float* d2, double best, int length )
40 double total_cost = 0;
41 assert( length % 4 == 0 );
42 for( int i = 0; i < length; i += 4 )
44 double t0 = d1[i ] - d2[i ];
45 double t1 = d1[i+1] - d2[i+1];
46 double t2 = d1[i+2] - d2[i+2];
47 double t3 = d1[i+3] - d2[i+3];
48 total_cost += t0*t0 + t1*t1 + t2*t2 + t3*t3;
49 if( total_cost > best )
57 naiveNearestNeighbor( const float* vec, int laplacian,
58 const CvSeq* model_keypoints,
59 const CvSeq* model_descriptors )
61 int length = (int)(model_descriptors->elem_size/sizeof(float));
63 double d, dist1 = 1e6, dist2 = 1e6;
64 CvSeqReader reader, kreader;
65 cvStartReadSeq( model_keypoints, &kreader, 0 );
66 cvStartReadSeq( model_descriptors, &reader, 0 );
68 for( i = 0; i < model_descriptors->total; i++ )
70 const CvSURFPoint* kp = (const CvSURFPoint*)kreader.ptr;
71 const float* mvec = (const float*)reader.ptr;
72 CV_NEXT_SEQ_ELEM( kreader.seq->elem_size, kreader );
73 CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
74 if( laplacian != kp->laplacian )
76 d = compareSURFDescriptors( vec, mvec, dist2, length );
86 if ( dist1 < 0.6*dist2 )
92 findPairs( const CvSeq* objectKeypoints, const CvSeq* objectDescriptors,
93 const CvSeq* imageKeypoints, const CvSeq* imageDescriptors, vector<int>& ptpairs )
96 CvSeqReader reader, kreader;
97 cvStartReadSeq( objectKeypoints, &kreader );
98 cvStartReadSeq( objectDescriptors, &reader );
101 for( i = 0; i < objectDescriptors->total; i++ )
103 const CvSURFPoint* kp = (const CvSURFPoint*)kreader.ptr;
104 const float* descriptor = (const float*)reader.ptr;
105 CV_NEXT_SEQ_ELEM( kreader.seq->elem_size, kreader );
106 CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
107 int nearest_neighbor = naiveNearestNeighbor( descriptor, kp->laplacian, imageKeypoints, imageDescriptors );
108 if( nearest_neighbor >= 0 )
110 ptpairs.push_back(i);
111 ptpairs.push_back(nearest_neighbor);
118 flannFindPairs( const CvSeq*, const CvSeq* objectDescriptors,
119 const CvSeq*, const CvSeq* imageDescriptors, vector<int>& ptpairs )
121 int length = (int)(objectDescriptors->elem_size/sizeof(float));
123 cv::Mat m_object(objectDescriptors->total, length, CV_32F);
124 cv::Mat m_image(imageDescriptors->total, length, CV_32F);
128 CvSeqReader obj_reader;
129 float* obj_ptr = m_object.ptr<float>(0);
130 cvStartReadSeq( objectDescriptors, &obj_reader );
131 for(int i = 0; i < objectDescriptors->total; i++ )
133 const float* descriptor = (const float*)obj_reader.ptr;
134 CV_NEXT_SEQ_ELEM( obj_reader.seq->elem_size, obj_reader );
135 memcpy(obj_ptr, descriptor, length*sizeof(float));
138 CvSeqReader img_reader;
139 float* img_ptr = m_image.ptr<float>(0);
140 cvStartReadSeq( imageDescriptors, &img_reader );
141 for(int i = 0; i < imageDescriptors->total; i++ )
143 const float* descriptor = (const float*)img_reader.ptr;
144 CV_NEXT_SEQ_ELEM( img_reader.seq->elem_size, img_reader );
145 memcpy(img_ptr, descriptor, length*sizeof(float));
149 // find nearest neighbors using FLANN
150 cv::Mat m_indices(objectDescriptors->total, 2, CV_32S);
151 cv::Mat m_dists(objectDescriptors->total, 2, CV_32F);
152 cv::flann::Index flann_index(m_image, cv::flann::KDTreeIndexParams(4)); // using 4 randomized kdtrees
153 flann_index.knnSearch(m_object, m_indices, m_dists, 2, cv::flann::SearchParams(64) ); // maximum number of leafs checked
155 int* indices_ptr = m_indices.ptr<int>(0);
156 float* dists_ptr = m_dists.ptr<float>(0);
157 for (int i=0;i<m_indices.rows;++i) {
158 if (dists_ptr[2*i]<0.6*dists_ptr[2*i+1]) {
159 ptpairs.push_back(i);
160 ptpairs.push_back(indices_ptr[2*i]);
166 /* a rough implementation for object location */
168 locatePlanarObject( const CvSeq* objectKeypoints, const CvSeq* objectDescriptors,
169 const CvSeq* imageKeypoints, const CvSeq* imageDescriptors,
170 const CvPoint src_corners[4], CvPoint dst_corners[4] )
173 CvMat _h = cvMat(3, 3, CV_64F, h);
175 vector<CvPoint2D32f> pt1, pt2;
180 flannFindPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
182 findPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
185 n = (int)(ptpairs.size()/2);
191 for( i = 0; i < n; i++ )
193 pt1[i] = ((CvSURFPoint*)cvGetSeqElem(objectKeypoints,ptpairs[i*2]))->pt;
194 pt2[i] = ((CvSURFPoint*)cvGetSeqElem(imageKeypoints,ptpairs[i*2+1]))->pt;
197 _pt1 = cvMat(1, n, CV_32FC2, &pt1[0] );
198 _pt2 = cvMat(1, n, CV_32FC2, &pt2[0] );
199 if( !cvFindHomography( &_pt1, &_pt2, &_h, CV_RANSAC, 5 ))
202 for( i = 0; i < 4; i++ )
204 double x = src_corners[i].x, y = src_corners[i].y;
205 double Z = 1./(h[6]*x + h[7]*y + h[8]);
206 double X = (h[0]*x + h[1]*y + h[2])*Z;
207 double Y = (h[3]*x + h[4]*y + h[5])*Z;
208 dst_corners[i] = cvPoint(cvRound(X), cvRound(Y));
214 int main(int argc, const char** argv)
218 CommandLineParser parser(argc, argv);
220 string objectFileName = parser.get<string>("object_filename", "box.png");
221 string sceneFileName = parser.get<string>("scene_filename", "box_in_scene.png");
223 CvMemStorage* storage = cvCreateMemStorage(0);
224 cvNamedWindow("Object", 1);
225 cvNamedWindow("Object Correspond", 1);
227 static CvScalar colors[] =
240 IplImage* object = cvLoadImage( objectFileName.c_str(), CV_LOAD_IMAGE_GRAYSCALE );
241 IplImage* image = cvLoadImage( sceneFileName.c_str(), CV_LOAD_IMAGE_GRAYSCALE );
242 if( !object || !image )
244 fprintf( stderr, "Can not load %s and/or %s\n", objectFileName.c_str(), sceneFileName.c_str() );
247 IplImage* object_color = cvCreateImage(cvGetSize(object), 8, 3);
248 cvCvtColor( object, object_color, CV_GRAY2BGR );
250 CvSeq *objectKeypoints = 0, *objectDescriptors = 0;
251 CvSeq *imageKeypoints = 0, *imageDescriptors = 0;
253 CvSURFParams params = cvSURFParams(500, 1);
255 double tt = (double)cvGetTickCount();
256 cvExtractSURF( object, 0, &objectKeypoints, &objectDescriptors, storage, params );
257 printf("Object Descriptors: %d\n", objectDescriptors->total);
258 cvExtractSURF( image, 0, &imageKeypoints, &imageDescriptors, storage, params );
259 printf("Image Descriptors: %d\n", imageDescriptors->total);
260 tt = (double)cvGetTickCount() - tt;
261 printf( "Extraction time = %gms\n", tt/(cvGetTickFrequency()*1000.));
262 CvPoint src_corners[4] = {{0,0}, {object->width,0}, {object->width, object->height}, {0, object->height}};
263 CvPoint dst_corners[4];
264 IplImage* correspond = cvCreateImage( cvSize(image->width, object->height+image->height), 8, 1 );
265 cvSetImageROI( correspond, cvRect( 0, 0, object->width, object->height ) );
266 cvCopy( object, correspond );
267 cvSetImageROI( correspond, cvRect( 0, object->height, correspond->width, correspond->height ) );
268 cvCopy( image, correspond );
269 cvResetImageROI( correspond );
272 printf("Using approximate nearest neighbor search\n");
275 if( locatePlanarObject( objectKeypoints, objectDescriptors, imageKeypoints,
276 imageDescriptors, src_corners, dst_corners ))
278 for( i = 0; i < 4; i++ )
280 CvPoint r1 = dst_corners[i%4];
281 CvPoint r2 = dst_corners[(i+1)%4];
282 cvLine( correspond, cvPoint(r1.x, r1.y+object->height ),
283 cvPoint(r2.x, r2.y+object->height ), colors[8] );
288 flannFindPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
290 findPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
292 for( i = 0; i < (int)ptpairs.size(); i += 2 )
294 CvSURFPoint* r1 = (CvSURFPoint*)cvGetSeqElem( objectKeypoints, ptpairs[i] );
295 CvSURFPoint* r2 = (CvSURFPoint*)cvGetSeqElem( imageKeypoints, ptpairs[i+1] );
296 cvLine( correspond, cvPointFrom32f(r1->pt),
297 cvPoint(cvRound(r2->pt.x), cvRound(r2->pt.y+object->height)), colors[8] );
300 cvShowImage( "Object Correspond", correspond );
301 for( i = 0; i < objectKeypoints->total; i++ )
303 CvSURFPoint* r = (CvSURFPoint*)cvGetSeqElem( objectKeypoints, i );
306 center.x = cvRound(r->pt.x);
307 center.y = cvRound(r->pt.y);
308 radius = cvRound(r->size*1.2/9.*2);
309 cvCircle( object_color, center, radius, colors[0], 1, 8, 0 );
311 cvShowImage( "Object", object_color );
315 cvDestroyWindow("Object");
316 cvDestroyWindow("Object Correspond");