|
1 |
| -import cv2 |
2 |
| - |
3 |
| -# Load the pre-trained Haar cascade for face detection |
4 |
| -face_cascade = cv2.CascadeClassifier(r'Intermediate\Face Dention Program\haarcascade_frontalface_default.xml') |
5 |
| - |
6 |
| -# Read the input image (use raw string for path) |
7 |
| -image_path = r'image.jpg' |
8 |
| - |
9 |
| -# Check if the image exists and is loaded properly |
10 |
| -image = cv2.imread(image_path) |
11 |
| -if image is None: |
12 |
| - print("Error: Could not open or find the image.") |
13 |
| - exit() |
14 |
| - |
15 |
| -# Convert the image to grayscale |
16 |
| -gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
17 |
| - |
18 |
| -# Detect faces in the image |
19 |
| -faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) |
20 |
| - |
21 |
| -# Draw rectangles around the faces |
22 |
| -for (x, y, w, h) in faces: |
23 |
| - cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2) |
24 |
| - |
25 |
| -# Display the result |
26 |
| -cv2.imshow('Face Detection', image) |
27 |
| - |
28 |
| -# Wait for a key press to close the window |
29 |
| -cv2.waitKey(0) |
30 |
| - |
31 |
| -# Save the result |
32 |
| -cv2.imwrite('Face_detected.jpg', image) |
33 |
| - |
34 |
| -# Close any open OpenCV windows |
35 |
| -cv2.destroyAllWindows() |
| 1 | +import cv2 |
| 2 | + |
| 3 | +# Load the pre-trained Haar Cascade classifier for face detection |
| 4 | +face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') |
| 5 | + |
| 6 | +# Start video capture from the webcam |
| 7 | +video_capture = cv2.VideoCapture(0) |
| 8 | + |
| 9 | +while True: |
| 10 | + # Capture frame-by-frame |
| 11 | + ret, frame = video_capture.read() |
| 12 | + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert to grayscale |
| 13 | + |
| 14 | + # Detect faces in the image |
| 15 | + faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) |
| 16 | + |
| 17 | + # Draw rectangles around detected faces |
| 18 | + for (x, y, w, h) in faces: |
| 19 | + cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) |
| 20 | + |
| 21 | + # Display the resulting frame |
| 22 | + cv2.imshow('Video', frame) |
| 23 | + |
| 24 | + # Break the loop on 'q' key press |
| 25 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 26 | + break |
| 27 | + |
| 28 | +# Release the capture and close windows |
| 29 | +video_capture.release() |
| 30 | +cv2.destroyAllWindows() |
0 commit comments