By Aman Kharwal

Face Detection using Webcam in Python

Simple Python Program to detect faces in a Webcam.

Face Detection using Open Source Computer Vision Library in python(OpenCv), we will use OpenCv in detection of our face using a webcam.

OpenCV is built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.

You can download the required Cascade Classifier from here

Let’s get Started with our code:

import cv2

# Load the cascade
face_cascade = cv2.CascadeClassifier('aman.xml')

# To capture video from webcam.
cap = cv2.VideoCapture(0)
while True:
    # Read the frame
    _, img =

    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Detect the faces
    faces = face_cascade.detectMultiScale(gray, 1.1, 4)

    # Draw the rectangle around each face
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (50, 50, 4), 10)

    # Display
    cv2.imshow('img', img)

    # Stop if escape key is pressed
    k = cv2.waitKey(30) & 0xff
    if k == 27:

# Release the VideoCapture object

It will open a you camera and you will see that your face is detected by the camera.

Leave a Reply