Sponser Link

How to detect face in opencv python with source code

This tutorial is about face detection in python. You will learn face detect in python using opencv library. We will draw a rectangle around the face.

import cv2

import sys

cascad_Path = "haarcascade_frontalface_default.xml"

faceCascade = cv2.CascadeClassifier(cascad_Path)

video_capture = cv2.VideoCapture(0)

while True:

    # Video capture frame by frame

    ret, frame = video_capture.read()

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

    faces = faceCascade.detectMultiScale(

        grayScale,

        scaleFactor=1.1,

        minNeighbors=5,

        minSize=(30, 30),

        flags=cv2.CASCADE_SCALE_IMAGE

    )

    # Draw a rectangle for highlight the face

    for (x, y, w, h) in faces:

        # Set RGB value for blue rectangle

        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

    # Display the resulting frame

    cv2.imshow('Video', frame)

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

        break

# When everything is done, release the capture

video_capture.release()

cv2.destroyAllWindows()