2023
Realtime face detection on web cam in Python using OpenCV
59
Open CV
Open CV is a powerful library that helps you in implementing many features like Automatic face detection , changing images to grayscale,image rotation and many more features related to images and videos. So here we will be using this for face detection on webcam realtime.
So we will add new python file and name it facedetection.py
Now copy the following piece of code for face detection
import cv2 import sys from time import sleep cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) video_capture = cv2.VideoCapture(0) anterior = 0 while True: if not video_capture.isOpened(): print('Unable to load camera.') sleep(5) pass # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) ) # Draw a rectangle around the faces for i,(x, y, w, h) in enumerate(faces): cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) face = frame[y:y+h, x:x+w] cv2.imwrite(f'face{i}.jpg', face) if anterior != len(faces): anterior = len(faces) # Display the resulting frame cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # Display the resulting frame cv2.imshow('Video', frame) # When everything is done, release the capture video_capture.release() cv2.destroyAllWindows()
Now save the file and open the command prompt and go to the location of file. Here first we have to install two packages.Run following command and press enter
pip install opencv-python==4.6.0.66
It will look like in the image below
Now install this second package
pip install opencv-contrib-python
You can check the command in below image
We this you will also need to add one xml file in the same location as your program. You can see the file in the image below You can download the files from the download button above.Now run the program and it will open the webcam on your system
You will be able to see the rectangle drawn on your webcam detecting your face. it will also save the detected face in the same location with name face0.jpg
So this is how we can implement realtime face detection on web cam in Python using OpenCV.