|
1 | 1 | import cv2
|
| 2 | +import os |
2 | 3 |
|
3 |
| -# Load the pre-trained Haar Cascade classifier for face detection |
4 |
| -face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') |
| 4 | +# Check if the XML file exists in the specified path |
| 5 | +if not os.path.isfile(r'C:\Users\dell\OneDrive\Documents\Programming\Python\Python_Begginer_Projects\Intermediate\Face Dention Program\haarcascade_frontalface_default.xml'): |
| 6 | + print("XML file not found!") |
| 7 | +else: |
| 8 | + print("XML file found!") |
5 | 9 |
|
6 |
| -# Start video capture from the webcam |
| 10 | +# Load the pre-trained Haar cascade for face detection |
| 11 | +face_cascade = cv2.CascadeClassifier(r'C:\Users\dell\OneDrive\Documents\Programming\Python\Python_Begginer_Projects\Intermediate\Face Dention Program\haarcascade_frontalface_default.xml') |
| 12 | + |
| 13 | +# Check if the cascade is loaded properly |
| 14 | +if face_cascade.empty(): |
| 15 | + raise IOError("Unable to load the cascade classifier xml file") |
| 16 | + |
| 17 | +# Initialize video capture from webcam (camera 0) |
7 | 18 | video_capture = cv2.VideoCapture(0)
|
8 | 19 |
|
9 | 20 | while True:
|
10 |
| - # Capture frame-by-frame |
11 | 21 | ret, frame = video_capture.read()
|
12 |
| - gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert to grayscale |
| 22 | + if not ret: |
| 23 | + print("Failed to capture frame") |
| 24 | + break |
| 25 | + |
| 26 | + # Convert the frame to grayscale |
| 27 | + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
13 | 28 |
|
14 | 29 | # Detect faces in the image
|
15 | 30 | faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
|
16 | 31 |
|
17 |
| - # Draw rectangles around detected faces |
| 32 | + # Draw rectangles around the faces |
18 | 33 | for (x, y, w, h) in faces:
|
19 |
| - cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) |
| 34 | + cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) |
20 | 35 |
|
21 | 36 | # Display the resulting frame
|
22 | 37 | cv2.imshow('Video', frame)
|
23 | 38 |
|
24 |
| - # Break the loop on 'q' key press |
| 39 | + # Break the loop when the 'q' key is pressed |
25 | 40 | if cv2.waitKey(1) & 0xFF == ord('q'):
|
26 | 41 | break
|
27 | 42 |
|
28 |
| -# Release the capture and close windows |
| 43 | +# Release the video capture object and close any OpenCV windows |
29 | 44 | video_capture.release()
|
30 | 45 | cv2.destroyAllWindows()
|
0 commit comments