Face Detection with OpenCV

In this first example we’ll learn how to apply face detection with OpenCV to the video.

First we need to import some required libraries

In [1]:
import os
import cv2
import argparse
import numpy as np
import matplotlib.pyplot as plt

We need to change the path to the path where our model and pictures are.

In [2]:
os.chdir("D:\\DataHacker.rs\\OpenCV Face Detection")

Define parameters:

In [3]:
# DNN stands for OpenCV: Deep Neural Networks
DNN = "TF" # Or CAFFE, or any other suported framework
min_confidence = 0.5 # minimum probability to filter weak detections

These files can be downloaded from the Internet, or created and trained manually.

For Caffe:

  • res10_300x300_ssd_iter_140000_fp16.caffemodel

  • deploy.prototxt

For Tensorflow:

  • opencv_face_detector_uint8.pb

  • opencv_face_detector.pbtxt

In [4]:
# load our serialized model from disk
print("[INFO] loading model...")

if DNN == "CAFFE":
    modelFile = "res10_300x300_ssd_iter_140000_fp16.caffemodel"
    configFile= "deploy.prototxt"
    
    # Here we need to read our pre-trained neural net created using Caffe
    net = cv2.dnn.readNetFromCaffe(configFile, modelFile)
else:
    modelFile = "opencv_face_detector_uint8.pb"
    configFile= "opencv_face_detector.pbtxt"
    
    # Here we need to read our pre-trained neural net created using Tensorflow
    net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
    
print("[INFO] model loaded.")
[INFO] loading model...
[INFO] model loaded.