Predictive Hacks

Computer Vision: Face Detection in OpenCV

computer vision

This post is a practical example of how we can use OpenCV with Python for detecting faces in a video. In a previous post, we explained how to apply Object Detection in Tensorflow and Face Detection in OpenCV. Generally, the Computer Vision and the Object Detection is a hot topic in Artificial Intelligence. Think for instance the autonomous vehicles which must detect continuously many different objects around them (pedestrians, other vehicles, signs etc).

How to Record a Video of Face Detection

In the following example, we apply a Face Detection with our USB Camera and we write the video to an .mp4 file. As you can see, the OpenCV is able to detect the face, and when it is hiding behind the hands the OpenCV is losing it.

import cv2
# change your path to the one where the haarcascades/haarcascade_frontalface_default.xml is
face_cascade = cv2.CascadeClassifier('../DATA/haarcascades/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0) 

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# MACOS AND LINUX: *'XVID' (MacOS users may want to try VIDX as well just in case)
# WINDOWS *'VIDX'
writer = cv2.VideoWriter('myface.mp4', cv2.VideoWriter_fourcc(*'XVID'),25, (width, height))


while True: 
    
    ret, frame = cap.read(0) 
     
    frame = detect_face(frame)
    writer.write(frame)
 
    cv2.imshow('Video Face Detection', frame) 
    # escape button to close it
    c = cv2.waitKey(1) 
    if c == 27: 
        break 
        
cap.release() 
writer.release()
cv2.destroyAllWindows()
 



The Output of the Computer Vision Code

Few lines of code are needed to record this video with the dynamic face detection. If you run the above block of code you will get a similar video (Of course with a different face 🙂 )

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

connect with sql
R

How to Connect R with SQL

Need to Connect R with SQL It is common for Data Analysts/Scientists to connect R with SQL. For that reason,

letter frequency
Python

Document Letter Frequency in Python

Letter Frequency We will provide you a walk-through example of how you can easily get the letter frequency in documents

[the_ad_group id="232"]
[the_ad id="2133"]