Follow

face detect using opencv python

1. Import the required modules: Start by importing the cv2 and cv2.face modules, which contain the functions for video capturing and face detection, respectively.
import cv2
import cv2.face
2. Load the face classifier: Use the cv2.CascadeClassifier function to load a pre-trained Haar cascade classifier for face detection. For example:
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
3. Open the camera: Use the cv2.VideoCapture function to open the default camera (camera index 0) or a specific camera by its index. For example:
cap = cv2.VideoCapture(0)
4. Check if the camera is opened: Verify if the camera was opened successfully by checking the return value of cap.isOpened(). If the camera is not opened, print an error message.
if not cap.isOpened():
print("Error opening camera")
5. Read frames: Use the cap.read function to read the frames from the camera. The function returns two values: a flag that indicates if the frame was read successfully, and the frame itself. For example:
ret, frame = cap.read()
6. Convert the frame to grayscale: Use the cv2.cvtColor function to convert the frame to grayscale, as the Haar cascade classifier requires grayscale images. For example:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
7. Detect faces: Use the face_cascade.detectMultiScale function to detect faces in the grayscale frame. The function returns a list of faces, represented as rectangles. For example:
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
8. Draw rectangles around the faces: Use a for loop and the cv2.rectangle function to draw rectangles around the faces. For example:
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
9. Display the frame: Use the cv2.imshow function to display the frame with rectangles around the faces in a window. For example:
cv2.imshow("Frame", frame)
10. Wait for key events: Use the cv2.waitKey function to wait for a key event and return its ASCII code. For example:
key = cv2.waitKey(1)
Break the loop: If a specific key is pressed, break the loop. For example, to break the loop if the 'q' key is pressed:
if key == ord('q'):
break
Release the camera: Use the cap.release function to release the camera after the loop
cap.release()
cv2.destroyAllWindows()

import cv2
import cv2.face
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error opening camera")
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

No comments:

Post a Comment

Tell us how you like it.