Friday, March 3, 2023

Python Face Detection

 You can use the OpenCV (Open Source Computer Vision Library) library to perform face detection in Python. OpenCV provides several pre-trained Haar classifiers for detecting various objects, including faces.


Here's an example code for face detection using OpenCV in Python:

import cv2 # Load the pre-trained Haar cascade classifier for face detection face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.XML) # Load the image to detect faces in img = cv2.imread('sample_image.jpg') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces in the grayscale image faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) # Draw rectangles around the detected faces for (x, y, w, h) in faces: cv2.rectangleimageg, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display the output image with detected faces cv2showw('Detected Faces', img) cv2.waitKey(0) cv2.destroyAllWindows()

In this code, we first load the pre-trained Haar cascade classifier for face detection. We then load an image and convert it to grayscale. We use the detectMultiScale method of the face cascade classifier to detect faces in the grayscale image. This method returns a list of rectangles, each corresponding to a detected face. We then draw rectangles around the detected faces using the cv2.rectangle method. Finally, we display the output image with the detected faces using the cv2.imshow method.

No comments:

Post a Comment

Featured Post

Python for Data Science: An Introduction to Pandas

Python has become the go-to language for data science due to its simplicity, flexibility, and powerful libraries. One such library is Pandas...

Popular Posts