Skip to content

Instantly share code, notes, and snippets.

@linhai86
Created October 14, 2018 20:29
Show Gist options
  • Save linhai86/326a1d0d6b60fc924666b122a93dd9e4 to your computer and use it in GitHub Desktop.
Save linhai86/326a1d0d6b60fc924666b122a93dd9e4 to your computer and use it in GitHub Desktop.
Simple script to capture webcam and detect faces.

Simple script to capture webcam and detect faces.

import cv2

def capture_webcam():
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    cap = cv2.VideoCapture(0)

    while(True):
        ret, frame = cap.read()

        frame = cv2.flip(frame, 1)

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

        faces = face_cascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30),
            flags=cv2.CASCADE_SCALE_IMAGE
        )

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


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

    cap.release()
    cv2.destroyAllWindows()
    cv2.waitKey(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment