OpenCV practice road - face detection (C++/Python)


This article is produced by @星神阁bingbuyu, please indicate the author and source for reprinting.

Article link: http://www.ifindbug.com/doc/id-48310/name-opencv-practice-road-face-detection-c-python.html

Weibo: http://weibo.com/xingchenbing 


I have always thought that face detection is very troublesome. Even with opencv, it is so troublesome that I dare not touch it. I took a closer look in the past two days. If you just call the classifiers and functions that come with opencv, it is simple. No, I'm just learning Python recently, so I just implemented it in both C++ and Python. Of course, this is the simplest version I have right now.


step:


The steps to call the opencv-trained classifier and the built-in detection function to detect faces and eyes are simple and straightforward:

1. Load the classifier, of course, the classifier must be placed in the project directory in advance. The original position of the classifier is in*\opencv\sources\data\haarcascades (harr classifier, there are others that can be used, or you can train yourself)

2. Call the detectMultiScale() function to detect, and adjust the parameters of the function to make the detection result more accurate.

3. Draw the detected faces with rectangles (or other shapes such as circles).


Main function:


The most important function here is detectMultiScale(). The explanation in the documentation is as follows:






1.image represents the input image to be detected

2.objects represents the detected face target sequence

3.scaleFactor represents the ratio of each image size reduction

4. minNeighbors means that each target must be detected at least 3 times to be considered a real target (because the surrounding pixels and different window sizes can bedetectto the human face),

5.minSize is the minimum size of the target

6.minSize is the maximum size of the target


Appropriate adjustment of the two parameters 4, 5, and 6 can be used to eliminate interference items in the detection results.


program:


The C++ program is as follows:

  1. # include <opencv2\opencv.hpp>
  2. # include <iostream>
  3. #include <stdio.h >
  4. using namespace std;
  5. using namespace cv;
  6. /** Function Headers */
  7. void detectAndDisplay (Mat frame) ;
  8. /** Global variables */
  9. String face_cascade_name = "haarcascade_frontalface_default.xml" ;
  10. String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml" ;
  11. CascadeClassifier face_cascade; //Define face classifier
  12. CascadeClassifier eyes_cascade; //Define the human eye classifier
  13. String window_name = "Capture - Face detection" ;
  14. /** @function main */
  15. int main ( void )
  16. {
  17. Mat frame = imread ( "2.jpg" );
  18. //VideoCapture capture;
  19. //Mat frame;
  20. //-- 1. Load the cascades
  21. if (!face_cascade.load ( face_cascade_name)){ printf ( "--(!)Error loading face cascade\n" ); return -1 ; };
  22. if (!eyes_cascade.load ( eyes_cascade_name)){ printf ( "--(!)Error loading eyes cascade\n" ); return -1 ; };
  23. //-- 2. Read the video stream
  24. //capture.open(0);
  25. //if (!capture.isOpened()) { printf("--(!)Error opening video capture\n"); return -1; }
  26. //while (capture.read(frame))
  27. //{
  28. // if (frame.empty())
  29. // {
  30. // printf(" --(!) No captured frame -- Break!");
  31. // break;
  32. // }
  33. //-- 3. Apply the classifier to the frame
  34. detectAndDisplay (frame);
  35. int c = waitKey ( 0 );
  36. if (( char )c == 27 ) { return 0 ; } // escape
  37. //}
  38. return 0 ;
  39. }
  40. /** @function detectAndDisplay */
  41. void detectAndDisplay (Mat frame)
  42. {
  43. std::vector<Rect> faces;
  44. Mat frame_gray;
  45. cvtColor (frame, frame_gray, COLOR_BGR2GRAY);
  46. equalizeHist (frame_gray, frame_gray);
  47. //-- Detect faces
  48. face_cascade.detectMultiScale ( frame_gray , faces, 1.1 , 3 , CV_HAAR_DO_ROUGH_SEARCH, Size ( 70 , 70 ), Size ( 100 , 100 ));
  49. for ( size_t i = 0 ; i < faces. size (); i++)
  50. {
  51. //Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
  52. //ellipse(frame, center, Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, Scalar(255, 0, 255), 4, 8, 0) ;
  53. rectangle (frame, faces[i], Scalar ( 255 , 0 , 0 ), 2 , 8 , 0 );
  54. Mat faceROI = frame_gray (faces[i]);
  55. std::vector<Rect> eyes;
  56. //-- In each face, detect eyes
  57. eyes_cascade.detectMultiScale ( faceROI , eyes, 1.1 , 1 , CV_HAAR_DO_ROUGH_SEARCH, Size ( 3 , 3 ));
  58. for ( size_t j = 0 ; j < eyes. size (); j++)
  59. {
  60. Rect rect (faces[i].x + eyes[j].x, faces[i].y + eyes[j].y, eyes[j].width, eyes[j].height) ;
  61. //Point eye_center(faces[i].x + eyes[j].x + eyes[j].width / 2, faces[i].y + eyes[j].y + eyes[j].height / 2 );
  62. //int radius = cvRound((eyes[j].width + eyes[j].height)*0.25);
  63. //circle(frame, eye_center, radius, Scalar(255, 0, 0), 4, 8, 0);
  64. rectangle (frame, rect, Scalar ( 0 , 255 , 0 ), 2 , 8 , 0 );
  65. }
  66. }
  67. //-- Show what you got
  68. namedWindow (window_name, 2 );
  69. imshow (window_name, frame);
  70. }


The Python program is as follows:

  1. import numpy as np
  2. import cv2
  3. face_cascade = cv2.CascadeClassifier( "/haarcascade_frontalface_default.xml" )
  4. eye_cascade = cv2.CascadeClassifier( "/haarcascade_eye_tree_eyeglasses.xml" )
  5. img = cv2.imread( "/2.jpg" )
  6. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  7. faces = face_cascade.detectMultiScale(gray, 1.1 , 5 ,cv2.CASCADE_SCALE_IMAGE,( 50 , 50 ),( 100 , 100 ))
  8. if len (faces)> 0 :
  9. for faceRect in faces:
  10. x,y,w,h = faceRect
  11. cv2.rectangle(img,(x,y),(x+w,y+h),( 255 , 0 , 0 ), 2 , 8 , 0 )
  12. roi_gray = gray[y:y+h,x:x+w]
  13. roi_color = img[y:y+h,x:x+w]
  14. eyes = eye_cascade.detectMultiScale(roi_gray, 1.1 , 1 ,cv2.CASCADE_SCALE_IMAGE,( 2 , 2 ))
  15. for (ex,ey,ew,eh) in eyes:
  16. cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),( 0 , 255 , 0 ), 2 )
  17. cv2.imshow( "img" ,img)
  18. cv2.waitKey( 0 )


Effect:


The final result is shown below:




planet of knowledge

In addition to the usual articles, I will also send some other reference materials and codes in the usual learning process. Welcome to join.




Tags: OpenCV practice road - face detection (C++/Python)

C++ Visual Studio OpenCV Python OpenCV practice road C++ opencv python Face Detection machine vision

Related: OpenCV practice road - face detection (C++/Python)