How To Face Detection With Python

It is a common use python opencv lib for face detection. But first you must install opencv library. for this please enter command below your command line:

pip install opencv-python

After that in a few second open cv library will installed to your computer. Now you can use code below to detect faces:

import cv2

# Load the pre-trained face detection model
face_cascade = cv2.CascadeClassifier( + 'haarcascade_frontalface_default.xml')

# Read the input image
image_path = 'path/to/your/image.jpg'
img = cv2.imread(image_path)

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

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

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

# Display the result
cv2.imshow('Detected Faces', img)

Make sure to replace 'path/to/your/image.jpg' with the actual path to the image you want to process. The haarcascade_frontalface_default.xml file is a pre-trained model for face detection provided by OpenCV.

Leave a Reply

Your email address will not be published. Required fields are marked *