Advertisement
j0h

gazedetect.cpp

j0h
Apr 3rd, 2023
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. #include <opencv2/opencv.hpp>
  2. #include <opencv2/core.hpp>
  3. #include <opencv2/highgui.hpp>
  4. #include <opencv2/imgproc.hpp>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8. using namespace cv;
  9.  
  10. int main(){
  11. // Load Haar cascades for face and eye detection
  12. CascadeClassifier face_cascade, eye_cascade;
  13. if (!face_cascade.load("haarcascade_frontalface_alt.xml") || !eye_cascade.load("haarcascade_eye.xml")) {
  14. cout << "Failed to load Haar cascades" << endl;
  15. return -1;
  16. }
  17.  
  18. // Open camera feed
  19. VideoCapture cap(0);
  20. if (!cap.isOpened()){
  21. cout << "Failed to open camera" << endl;
  22. return -1;
  23. }
  24.  
  25. // Loop through frames
  26. while (true){
  27. Mat frame;
  28. cap >> frame;
  29.  
  30. // Convert frame to grayscale for face and eye detection
  31. Mat gray_frame;
  32. cvtColor(frame, gray_frame, COLOR_BGR2GRAY);
  33.  
  34. // Detect faces
  35. vector<Rect> faces;
  36. face_cascade.detectMultiScale(gray_frame, faces, 1.3, 5);
  37.  
  38. // Loop through faces
  39. for (size_t i = 0; i < faces.size(); i++){
  40. Rect face_rect = faces[i];
  41.  
  42. // Draw rectangle around face
  43. rectangle(frame, face_rect, Scalar(255, 0, 0), 2);
  44.  
  45. // Extract ROI for face
  46. Mat face_roi = gray_frame(face_rect);
  47.  
  48. // Detect eyes within face ROI (region of interest)
  49. vector<Rect> eyes;
  50. eye_cascade.detectMultiScale(face_roi, eyes, 1.3, 5);
  51.  
  52. // Loop through eyes
  53. for (size_t j = 0; j < eyes.size(); j++){
  54. Rect eye_rect = eyes[j];
  55.  
  56. // Draw rectangle around eye
  57. rectangle(frame, Point(face_rect.x + eye_rect.x, face_rect.y + eye_rect.y),
  58. Point(face_rect.x + eye_rect.x + eye_rect.width, face_rect.y + eye_rect.y + eye_rect.height),
  59. Scalar(0, 255, 0), 2);
  60.  
  61. // Calculate center of eye
  62. Point eye_center(face_rect.x + eye_rect.x + eye_rect.width / 2, face_rect.y + eye_rect.y + eye_rect.height / 2);
  63.  
  64. // Draw circle at center of eye
  65. circle(frame, eye_center, 2, Scalar(0, 0, 255), 2);
  66. }
  67. }
  68.  
  69. // Show frame
  70. imshow("Gaze Detection", frame);
  71.  
  72. // Exit on key press
  73. if (waitKey(1) == 27) break;
  74. }
  75.  
  76. return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement