/VisualC++数字图像处理技术详解源代码/第12章 VC++结合OpenCV编程/FaceDetection.cpp

https://github.com/wyrover/book-code · C++ · 78 lines · 66 code · 9 blank · 3 comment · 3 complexity · 16115ea82c9810ce9f0881874cd9059b MD5 · raw file

  1. // FaceDetection.cpp : ̨Ӧóڵ㡣
  2. //
  3. #include "stdafx.h"
  4. #include "cv.h"
  5. #include "highgui.h"
  6. #include <stdio.h>
  7. static CvHaarClassifierCascade* cascade = 0;
  8. static CvMemStorage* storage = 0;
  9. void detect_and_draw( IplImage* image );
  10. const char* cascade_name ="haarcascade_frontalface_alt.xml"; //Ҫõķ
  11. int _tmain(int argc, _TCHAR* argv[])
  12. {
  13. cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 ); //õķ
  14. if( !cascade )
  15. {
  16. fprintf( stderr, "ERROR: Could not load classifier cascade\n" );
  17. return -1;
  18. }
  19. storage = cvCreateMemStorage(0); //̬洢ṹ洢ͼеλ
  20. cvNamedWindow( "result", 1 );
  21. const char* filename = "lena.jpg"; //ͼ
  22. IplImage* image = cvLoadImage( filename, 1 ); //ͼ
  23. detect_and_draw( image ); //Լصͼм
  24. cvWaitKey(0);
  25. cvReleaseImage( &image );
  26. cvDestroyWindow("result");
  27. return 0;
  28. }
  29. void detect_and_draw( IplImage* img )
  30. {
  31. static CvScalar colors[] =
  32. {
  33. {{0,0,255}},
  34. {{0,128,255}},
  35. {{0,255,255}},
  36. {{0,255,0}},
  37. {{255,128,0}},
  38. {{255,255,0}},
  39. {{255,0,0}},
  40. {{255,0,255}}
  41. };
  42. double scale = 1.3;
  43. IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
  44. IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
  45. cvRound (img->height/scale)), 8, 1 );
  46. cvCvtColor( img, gray, CV_BGR2GRAY );
  47. cvResize( gray, small_img, CV_INTER_LINEAR );
  48. cvEqualizeHist( small_img, small_img );
  49. cvClearMemStorage( storage );
  50. if( cascade )
  51. {
  52. /*cvHaarDetectObjectsͼеĿ꣬OpenCVṩ*/
  53. CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage, 1.1, 2, 0 ,
  54. cvSize(30, 30) );
  55. for( int i = 0; i < (faces ? faces->total : 0); i++ )
  56. {
  57. CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
  58. CvPoint center;
  59. int radius;
  60. center.x = cvRound((r->x + r->width*0.5)*scale);
  61. center.y = cvRound((r->y + r->height*0.5)*scale);
  62. radius = cvRound((r->width + r->height)*0.25*scale);
  63. cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );
  64. }
  65. }
  66. cvShowImage( "result", img );
  67. cvReleaseImage( &gray );
  68. cvReleaseImage( &small_img );
  69. }