|
| 1 | +#Face and Eye Detection |
| 2 | +import cv2 |
| 3 | + |
| 4 | +#PATH of the FILE |
| 5 | +CLASSIFIER_PATH = "./Facedetection/v2/haarcascade_frontalface_default.xml" |
| 6 | +EYEDETECTION_PATH = "./Facedetection/v2/haarcascade_eye.xml" |
| 7 | + |
| 8 | +# Live video capturing |
| 9 | +cam = cv2.VideoCapture(0) |
| 10 | + |
| 11 | +# Initializing classifier |
| 12 | +face_classifier = cv2.CascadeClassifier(CLASSIFIER_PATH) |
| 13 | +EYE_DETECTION = cv2.CascadeClassifier(EYEDETECTION_PATH) |
| 14 | + |
| 15 | +while (True): |
| 16 | + |
| 17 | + _, frame = cam.read() |
| 18 | + |
| 19 | + # Converting to grayscale image |
| 20 | + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
| 21 | + |
| 22 | + # Returns coordinates of all faces in the frame |
| 23 | + faces = face_classifier.detectMultiScale(gray, 1.3, 5) |
| 24 | + # Cycle through each coordinate list |
| 25 | + for (x, y, w, h) in faces: |
| 26 | + |
| 27 | + # Extracting mid points of bounding box |
| 28 | + mid_x = int(x + h/2) |
| 29 | + mid_y = int(y + h/2) |
| 30 | + |
| 31 | + # Drawing - "bounding box" |
| 32 | + frame = cv2.rectangle(frame, (x, y), (x + h, y + h), (255, 0, 0), 2) |
| 33 | + # 'x-coordinate' on live feed |
| 34 | + frame = cv2.putText(frame, str(x), (x, y), cv2.FONT_HERSHEY_DUPLEX, 0.7, (0, 0, 255), 2) |
| 35 | + # "." represent mid part in face |
| 36 | + frame = cv2.putText(frame, ".", (mid_x, mid_y), cv2.FONT_HERSHEY_DUPLEX, 0.7, (0, 0, 255), 2) |
| 37 | + |
| 38 | + #Detects The Eyes |
| 39 | + eyes = EYE_DETECTION.detectMultiScale(gray, 1.3, 5) |
| 40 | + for (ex,ey,ew,eh) in eyes: |
| 41 | + cv2.rectangle(frame, (ex,ey), (ex+eh, ey+eh), (0,255,0), 2) |
| 42 | + |
| 43 | + |
| 44 | + # Displaying video feed with detected faces |
| 45 | + cv2.imshow('Frame', frame) |
| 46 | + |
| 47 | + # Reading for keyboard interrupts |
| 48 | + key = cv2.waitKey(1) |
| 49 | + if (key == 27): |
| 50 | + break |
| 51 | + |
| 52 | +cam.release() |
| 53 | +cv2.destroyAllWindows() |
0 commit comments