PageRenderTime 37ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/opencv_device/share/opencv/samples/c/find_obj.cpp

https://github.com/BynreForest/FaceDetection
C++ | 308 lines | 257 code | 41 blank | 10 comment | 28 complexity | 976968aa9d2e3e20d3cb9d4dad7b3e92 MD5 | raw file
  1. /*
  2. * A Demo to OpenCV Implementation of SURF
  3. * Further Information Refer to "SURF: Speed-Up Robust Feature"
  4. * Author: Liu Liu
  5. * liuliu.1987+opencv@gmail.com
  6. */
  7. #include <cv.h>
  8. #include <highgui.h>
  9. #include <ctype.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <iostream>
  13. #include <vector>
  14. using namespace std;
  15. // define whether to use approximate nearest-neighbor search
  16. #define USE_FLANN
  17. IplImage *image = 0;
  18. double
  19. compareSURFDescriptors( const float* d1, const float* d2, double best, int length )
  20. {
  21. double total_cost = 0;
  22. assert( length % 4 == 0 );
  23. for( int i = 0; i < length; i += 4 )
  24. {
  25. double t0 = d1[i] - d2[i];
  26. double t1 = d1[i+1] - d2[i+1];
  27. double t2 = d1[i+2] - d2[i+2];
  28. double t3 = d1[i+3] - d2[i+3];
  29. total_cost += t0*t0 + t1*t1 + t2*t2 + t3*t3;
  30. if( total_cost > best )
  31. break;
  32. }
  33. return total_cost;
  34. }
  35. int
  36. naiveNearestNeighbor( const float* vec, int laplacian,
  37. const CvSeq* model_keypoints,
  38. const CvSeq* model_descriptors )
  39. {
  40. int length = (int)(model_descriptors->elem_size/sizeof(float));
  41. int i, neighbor = -1;
  42. double d, dist1 = 1e6, dist2 = 1e6;
  43. CvSeqReader reader, kreader;
  44. cvStartReadSeq( model_keypoints, &kreader, 0 );
  45. cvStartReadSeq( model_descriptors, &reader, 0 );
  46. for( i = 0; i < model_descriptors->total; i++ )
  47. {
  48. const CvSURFPoint* kp = (const CvSURFPoint*)kreader.ptr;
  49. const float* mvec = (const float*)reader.ptr;
  50. CV_NEXT_SEQ_ELEM( kreader.seq->elem_size, kreader );
  51. CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
  52. if( laplacian != kp->laplacian )
  53. continue;
  54. d = compareSURFDescriptors( vec, mvec, dist2, length );
  55. if( d < dist1 )
  56. {
  57. dist2 = dist1;
  58. dist1 = d;
  59. neighbor = i;
  60. }
  61. else if ( d < dist2 )
  62. dist2 = d;
  63. }
  64. if ( dist1 < 0.6*dist2 )
  65. return neighbor;
  66. return -1;
  67. }
  68. void
  69. findPairs( const CvSeq* objectKeypoints, const CvSeq* objectDescriptors,
  70. const CvSeq* imageKeypoints, const CvSeq* imageDescriptors, vector<int>& ptpairs )
  71. {
  72. int i;
  73. CvSeqReader reader, kreader;
  74. cvStartReadSeq( objectKeypoints, &kreader );
  75. cvStartReadSeq( objectDescriptors, &reader );
  76. ptpairs.clear();
  77. for( i = 0; i < objectDescriptors->total; i++ )
  78. {
  79. const CvSURFPoint* kp = (const CvSURFPoint*)kreader.ptr;
  80. const float* descriptor = (const float*)reader.ptr;
  81. CV_NEXT_SEQ_ELEM( kreader.seq->elem_size, kreader );
  82. CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
  83. int nearest_neighbor = naiveNearestNeighbor( descriptor, kp->laplacian, imageKeypoints, imageDescriptors );
  84. if( nearest_neighbor >= 0 )
  85. {
  86. ptpairs.push_back(i);
  87. ptpairs.push_back(nearest_neighbor);
  88. }
  89. }
  90. }
  91. void
  92. flannFindPairs( const CvSeq*, const CvSeq* objectDescriptors,
  93. const CvSeq*, const CvSeq* imageDescriptors, vector<int>& ptpairs )
  94. {
  95. int length = (int)(objectDescriptors->elem_size/sizeof(float));
  96. cv::Mat m_object(objectDescriptors->total, length, CV_32F);
  97. cv::Mat m_image(imageDescriptors->total, length, CV_32F);
  98. // copy descriptors
  99. CvSeqReader obj_reader;
  100. float* obj_ptr = m_object.ptr<float>(0);
  101. cvStartReadSeq( objectDescriptors, &obj_reader );
  102. for(int i = 0; i < objectDescriptors->total; i++ )
  103. {
  104. const float* descriptor = (const float*)obj_reader.ptr;
  105. CV_NEXT_SEQ_ELEM( obj_reader.seq->elem_size, obj_reader );
  106. memcpy(obj_ptr, descriptor, length*sizeof(float));
  107. obj_ptr += length;
  108. }
  109. CvSeqReader img_reader;
  110. float* img_ptr = m_image.ptr<float>(0);
  111. cvStartReadSeq( imageDescriptors, &img_reader );
  112. for(int i = 0; i < imageDescriptors->total; i++ )
  113. {
  114. const float* descriptor = (const float*)img_reader.ptr;
  115. CV_NEXT_SEQ_ELEM( img_reader.seq->elem_size, img_reader );
  116. memcpy(img_ptr, descriptor, length*sizeof(float));
  117. img_ptr += length;
  118. }
  119. // find nearest neighbors using FLANN
  120. cv::Mat m_indices(objectDescriptors->total, 2, CV_32S);
  121. cv::Mat m_dists(objectDescriptors->total, 2, CV_32F);
  122. cv::flann::Index flann_index(m_image, cv::flann::KDTreeIndexParams(4)); // using 4 randomized kdtrees
  123. flann_index.knnSearch(m_object, m_indices, m_dists, 2, cv::flann::SearchParams(64) ); // maximum number of leafs checked
  124. int* indices_ptr = m_indices.ptr<int>(0);
  125. float* dists_ptr = m_dists.ptr<float>(0);
  126. for (int i=0;i<m_indices.rows;++i) {
  127. if (dists_ptr[2*i]<0.6*dists_ptr[2*i+1]) {
  128. ptpairs.push_back(i);
  129. ptpairs.push_back(indices_ptr[2*i]);
  130. }
  131. }
  132. }
  133. /* a rough implementation for object location */
  134. int
  135. locatePlanarObject( const CvSeq* objectKeypoints, const CvSeq* objectDescriptors,
  136. const CvSeq* imageKeypoints, const CvSeq* imageDescriptors,
  137. const CvPoint src_corners[4], CvPoint dst_corners[4] )
  138. {
  139. double h[9];
  140. CvMat _h = cvMat(3, 3, CV_64F, h);
  141. vector<int> ptpairs;
  142. vector<CvPoint2D32f> pt1, pt2;
  143. CvMat _pt1, _pt2;
  144. int i, n;
  145. #ifdef USE_FLANN
  146. flannFindPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
  147. #else
  148. findPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
  149. #endif
  150. n = ptpairs.size()/2;
  151. if( n < 4 )
  152. return 0;
  153. pt1.resize(n);
  154. pt2.resize(n);
  155. for( i = 0; i < n; i++ )
  156. {
  157. pt1[i] = ((CvSURFPoint*)cvGetSeqElem(objectKeypoints,ptpairs[i*2]))->pt;
  158. pt2[i] = ((CvSURFPoint*)cvGetSeqElem(imageKeypoints,ptpairs[i*2+1]))->pt;
  159. }
  160. _pt1 = cvMat(1, n, CV_32FC2, &pt1[0] );
  161. _pt2 = cvMat(1, n, CV_32FC2, &pt2[0] );
  162. if( !cvFindHomography( &_pt1, &_pt2, &_h, CV_RANSAC, 5 ))
  163. return 0;
  164. for( i = 0; i < 4; i++ )
  165. {
  166. double x = src_corners[i].x, y = src_corners[i].y;
  167. double Z = 1./(h[6]*x + h[7]*y + h[8]);
  168. double X = (h[0]*x + h[1]*y + h[2])*Z;
  169. double Y = (h[3]*x + h[4]*y + h[5])*Z;
  170. dst_corners[i] = cvPoint(cvRound(X), cvRound(Y));
  171. }
  172. return 1;
  173. }
  174. int main(int argc, char** argv)
  175. {
  176. const char* object_filename = argc == 3 ? argv[1] : "box.png";
  177. const char* scene_filename = argc == 3 ? argv[2] : "box_in_scene.png";
  178. CvMemStorage* storage = cvCreateMemStorage(0);
  179. cvNamedWindow("Object", 1);
  180. cvNamedWindow("Object Correspond", 1);
  181. static CvScalar colors[] =
  182. {
  183. {{0,0,255}},
  184. {{0,128,255}},
  185. {{0,255,255}},
  186. {{0,255,0}},
  187. {{255,128,0}},
  188. {{255,255,0}},
  189. {{255,0,0}},
  190. {{255,0,255}},
  191. {{255,255,255}}
  192. };
  193. IplImage* object = cvLoadImage( object_filename, CV_LOAD_IMAGE_GRAYSCALE );
  194. IplImage* image = cvLoadImage( scene_filename, CV_LOAD_IMAGE_GRAYSCALE );
  195. if( !object || !image )
  196. {
  197. fprintf( stderr, "Can not load %s and/or %s\n"
  198. "Usage: find_obj [<object_filename> <scene_filename>]\n",
  199. object_filename, scene_filename );
  200. exit(-1);
  201. }
  202. IplImage* object_color = cvCreateImage(cvGetSize(object), 8, 3);
  203. cvCvtColor( object, object_color, CV_GRAY2BGR );
  204. CvSeq *objectKeypoints = 0, *objectDescriptors = 0;
  205. CvSeq *imageKeypoints = 0, *imageDescriptors = 0;
  206. int i;
  207. CvSURFParams params = cvSURFParams(500, 1);
  208. double tt = (double)cvGetTickCount();
  209. cvExtractSURF( object, 0, &objectKeypoints, &objectDescriptors, storage, params );
  210. printf("Object Descriptors: %d\n", objectDescriptors->total);
  211. cvExtractSURF( image, 0, &imageKeypoints, &imageDescriptors, storage, params );
  212. printf("Image Descriptors: %d\n", imageDescriptors->total);
  213. tt = (double)cvGetTickCount() - tt;
  214. printf( "Extraction time = %gms\n", tt/(cvGetTickFrequency()*1000.));
  215. CvPoint src_corners[4] = {{0,0}, {object->width,0}, {object->width, object->height}, {0, object->height}};
  216. CvPoint dst_corners[4];
  217. IplImage* correspond = cvCreateImage( cvSize(image->width, object->height+image->height), 8, 1 );
  218. cvSetImageROI( correspond, cvRect( 0, 0, object->width, object->height ) );
  219. cvCopy( object, correspond );
  220. cvSetImageROI( correspond, cvRect( 0, object->height, correspond->width, correspond->height ) );
  221. cvCopy( image, correspond );
  222. cvResetImageROI( correspond );
  223. #ifdef USE_FLANN
  224. printf("Using approximate nearest neighbor search\n");
  225. #endif
  226. if( locatePlanarObject( objectKeypoints, objectDescriptors, imageKeypoints,
  227. imageDescriptors, src_corners, dst_corners ))
  228. {
  229. for( i = 0; i < 4; i++ )
  230. {
  231. CvPoint r1 = dst_corners[i%4];
  232. CvPoint r2 = dst_corners[(i+1)%4];
  233. cvLine( correspond, cvPoint(r1.x, r1.y+object->height ),
  234. cvPoint(r2.x, r2.y+object->height ), colors[8] );
  235. }
  236. }
  237. vector<int> ptpairs;
  238. #ifdef USE_FLANN
  239. flannFindPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
  240. #else
  241. findPairs( objectKeypoints, objectDescriptors, imageKeypoints, imageDescriptors, ptpairs );
  242. #endif
  243. for( i = 0; i < (int)ptpairs.size(); i += 2 )
  244. {
  245. CvSURFPoint* r1 = (CvSURFPoint*)cvGetSeqElem( objectKeypoints, ptpairs[i] );
  246. CvSURFPoint* r2 = (CvSURFPoint*)cvGetSeqElem( imageKeypoints, ptpairs[i+1] );
  247. cvLine( correspond, cvPointFrom32f(r1->pt),
  248. cvPoint(cvRound(r2->pt.x), cvRound(r2->pt.y+object->height)), colors[8] );
  249. }
  250. cvShowImage( "Object Correspond", correspond );
  251. for( i = 0; i < objectKeypoints->total; i++ )
  252. {
  253. CvSURFPoint* r = (CvSURFPoint*)cvGetSeqElem( objectKeypoints, i );
  254. CvPoint center;
  255. int radius;
  256. center.x = cvRound(r->pt.x);
  257. center.y = cvRound(r->pt.y);
  258. radius = cvRound(r->size*1.2/9.*2);
  259. cvCircle( object_color, center, radius, colors[0], 1, 8, 0 );
  260. }
  261. cvShowImage( "Object", object_color );
  262. cvWaitKey(0);
  263. cvDestroyWindow("Object");
  264. cvDestroyWindow("Object SURF");
  265. cvDestroyWindow("Object Correspond");
  266. return 0;
  267. }