ninjaEyeDetector.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "opencv2/opencv.hpp"
  2. using namespace cv;
  3. using namespace std;
  4. // Specifying minimum and maximum size parameters
  5. #define MIN_FACE_SIZE 100
  6. #define MAX_FACE_SIZE 300
  7. int main(void){
  8. // Load the Cascade Classifier Xml file
  9. CascadeClassifier faceCascade("cascade/mallick_haarcascade_frontalface_default.xml");
  10. // Create a VideoCapture object
  11. VideoCapture cap;
  12. // Check if camera opened successfully
  13. if(!cap.open(0)) return 0;
  14. Mat frame, frameBig, frameGray;
  15. while (1){
  16. // Reading each frame
  17. bool frameRead = cap.read(frameBig);
  18. // If frame not opened successfully
  19. if (!frameRead)
  20. break;
  21. // Fixing the scaling factor
  22. float scale = 640.0f/frameBig.cols;
  23. // Resizing the image
  24. resize(frameBig, frame, Size(), scale, scale);
  25. // Converting to grayscale
  26. cvtColor(frame, frameGray, COLOR_BGR2GRAY);
  27. // Creating vector to store the detected faces' parameters
  28. vector<Rect> faces;
  29. // Detect faces
  30. faceCascade.detectMultiScale(frameGray,faces,1.1,5,0,Size(MIN_FACE_SIZE,MIN_FACE_SIZE),Size(MAX_FACE_SIZE,MAX_FACE_SIZE));
  31. // Loop over each detected face
  32. for ( int i = 0; i < faces.size(); i++)
  33. {
  34. // Dimension parameters for bounding rectangle for face
  35. Rect faceRect = faces[i];
  36. // Calculating the dimension parameters for eyes from the dimensions parameters of the face
  37. Rect eyesRect = Rect(faceRect.x + 0.125*faceRect.width,faceRect.y + 0.25 * faceRect.height,0.75 * faceRect.width,
  38. 0.25 * faceRect.height);
  39. // Drawing the bounding rectangle around the face
  40. rectangle(frame, eyesRect,Scalar(128,255,0), 2);
  41. }
  42. // Display the resulting frame
  43. imshow("Ninja Eye Detector", frame);
  44. int k = waitKey(1);
  45. // Press ESC on keyboard to stop tracking
  46. if(k == 27)
  47. break;
  48. }
  49. // release the VideoCapture object
  50. cap.release();
  51. // Closes all the windows
  52. destroyAllWindows();
  53. return 0;
  54. }