DEV Community

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

Posted on • Edited on

2 2

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

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay