Environment

  • Python 2.7.15
  • Windows 10
  • opencv 3.4.3
  • webcam

Steps

  1. Start command prompt
  2. Clone the repository
    git clone https://github.com/shantnu/Webcam-Face-Detect.git
    
  3. Change to the project folder
    cd Webcam-Face-Detect
    
  4. Create virtual environment
    virtualenv env
    
  5. Enter env virtual environment
    env\Scripts\activate.bat
    
  6. Go to the sourceforge site. Enter opencv-win category and download opencv-3.4.3-vc14_vc15.exe. Extract it.
  7. Copy C:\Users\user\Downloads\opencv\build\python\2.7\x64\cv2.pyd to the directory C:\Python27\Lib\site-packages
  8. Start Python IDLE and type:
    import cv2
    print cv2.__version__
    
  9. Restart command prompt
  10. Change to the project folder
    cd Webcam-Face-Detect
    
  11. Create webcam_cv3.py.
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

# Or video filename as parameter
# Opencv can not decode compressed video, install ffmpeg to decode.
video_capture = cv2.VideoCapture(0)
#Front
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

	# scaleFactor 10%, 1.05 = 5% increase the chance of a matching size
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)


    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

  1. Fire face detection
    C:\Python27\python webcam_cv3.py
    
  2. Face detection from a video file
    video_capture = cv2.VideoCapture("Top 15 Funniest Friends Moments.mp4")
    

    python-face-detection-video

  3. You can find more OpenCV’s pre-trained classifiers in C:\Users\user\Downloads\opencv\sources\data\haarcascades folder

Reference