DEV Community

Cover image for Detect Faces in Video using OpenCV
Ganesh Raja
Ganesh Raja

Posted on • Updated on

Detect Faces in Video using OpenCV

So, Today I wanted to experiment with Simple OpenCV. So that the following script does is,
it loads the video from the disk, checks for face shape in every frame using the loaded cascade. if it finds an image, it draws a rectangle around it and displays the image. Unfortunately, it only detects frontal faces.

You can find the code to do this below

You can find my Repo Link here
https://github.com/ganeshraja10/Latest-Tech-Learnings

import cv2
# loading haarcascade to detect frontal face
cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

video = cv2.VideoCapture('data/avengers.mp4')  # Load video

while True:
    rect, img = video.read()  # Read the video
    if not rect:
        break
    # Convert RGB to Gray to detect edges
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = cascade.detectMultiScale(gray, 1.35, 7)  # Detect possible faces
    if faces is not ():  # List is not empty
        for x, y, w, h in faces:  # Draw Rect in all faces
            cv2.rectangle(img, (x, y), (x+w, y+h), (127, 0, 255), 2)
    cv2.imshow('img', img)  # Display the image
    k = cv2.waitKey(30)
    if k == 27:  # if key pressed is escape quit
        break

video.release()  # release the video

Enter fullscreen mode Exit fullscreen mode

Top comments (0)