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 🙂 )