1- ## Name - Soumyajit Chakraborty
2- ## place - kolkata
3- ## date - 10 / 08 / 2020
4-
51import cv2 as cv
62
7- face_cascade = cv .CascadeClassifier ("..\libs\haarcascade_frontalface_default.xml" )
8- face_cascade_eye = cv .CascadeClassifier ("..\libs\haarcascade_eye.xml" )
9- # face_glass = cv.CascadeClassifier('..\libs\haarcascade_eye_tree_eyeglasses.xml')
10-
11- cap = cv .VideoCapture (0 )
12- while cap .isOpened ():
13-
14- falg , img = cap .read () # start reading the camera output i mean frames
15- # cap.read() returning a bool value and a frame onject type value
16-
17- gray = cv .cvtColor (
18- img , cv .COLOR_BGR2GRAY
19- ) # converting to grayscale image to perform smoother
20- faces = face_cascade .detectMultiScale (
21- img , 1.1 , 7
22- ) # we use detectMultiscale library function to detect the predefined structures of a face
23- eyes = face_cascade_eye .detectMultiScale (img , 1.1 , 7 )
24- # using for loops we are trying to read each and every frame and map
25- for (x , y , w , h ) in faces :
26- cv .rectangle (img , (x , y ), (x + w , y + h ), (0 , 255 , 0 ), 1 )
27-
28- for (a , b , c , d ) in eyes :
29- cv .rectangle (img , (a , b ), (a + c , b + d ), (255 , 0 , 0 ), 1 )
30-
31- cv .imshow ("img" , img )
32- c = cv .waitKey (1 )
33- if c == ord ("q" ):
34- break
35-
36- cv .release ()
37- cv .destroyAllWindows ()
3+
4+ def detect_faces_and_eyes ():
5+ """
6+ Detects faces and eyes in real-time using the webcam.
7+
8+ Press 'q' to exit the program.
9+ """
10+ # Load the pre-trained classifiers for face and eye detection
11+ face_cascade = cv .CascadeClassifier (r"..\libs\haarcascade_frontalface_default.xml" )
12+ eye_cascade = cv .CascadeClassifier (r"..\libs\haarcascade_eye.xml" )
13+
14+ # Open the webcam
15+ cap = cv .VideoCapture (0 )
16+
17+ while cap .isOpened ():
18+ # Read a frame from the webcam
19+ flag , img = cap .read ()
20+
21+ # Convert the frame to grayscale for better performance
22+ gray = cv .cvtColor (img , cv .COLOR_BGR2GRAY )
23+
24+ # Detect faces in the frame
25+ faces = face_cascade .detectMultiScale (gray , scaleFactor = 1.1 , minNeighbors = 7 )
26+
27+ # Detect eyes in the frame
28+ eyes = eye_cascade .detectMultiScale (gray , scaleFactor = 1.1 , minNeighbors = 7 )
29+
30+ # Draw rectangles around faces and eyes
31+ for x , y , w , h in faces :
32+ cv .rectangle (img , (x , y ), (x + w , y + h ), (0 , 255 , 0 ), 1 )
33+
34+ for a , b , c , d in eyes :
35+ cv .rectangle (img , (a , b ), (a + c , b + d ), (255 , 0 , 0 ), 1 )
36+
37+ # Display the resulting frame
38+ cv .imshow ("Face and Eye Detection" , img )
39+
40+ # Check for the 'q' key to exit the program
41+ key = cv .waitKey (1 )
42+ if key == ord ("q" ):
43+ break
44+
45+ # Release the webcam and close all windows
46+ cap .release ()
47+ cv .destroyAllWindows ()
48+
49+
50+ if __name__ == "__main__" :
51+ # Call the main function
52+ detect_faces_and_eyes ()
0 commit comments