![]() |
Photo by Marily Torres from Pexels |
In this post, I wanted to share a very easy and popular way of face
detecting using Haar cascades in OpenCV and python.
First, install python on your computer
To download python [click here]
Now install OpenCV. You can install it by using the pip command in
python
pip install opencv-python
Face detection using Haar cascades is a machine learning-based approach
where a cascade function is trained with a group of the input file.
OpenCV has many classifiers for face, eyes, smiles, etc. Today we'll be
using the face classifier. You'll be able to experiment with other
classifiers also.
You need to download
the trained classifier XML file (haarcascade_frontalface_default.xml), which is out there in
OpenCV's GitHub repository. Save it to your working location.
Our setup is done now let's start to code
Don't worry, just paste this code into Notepad
Code for detect face in the image
import cv2 # Load the cascade face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Read the input image img = cv2.imread('test.jpg') # Convert into grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces faces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (10, 55, 255), 6) # Display the output cv2.imshow('img', img) cv2.waitKey()
save your file as yourname.py
Place the image in your workspace which you want to detect face it must
be in "PNG" format, and it must be named as "test"
Just double-click the file to run your program
If you want to use a JPG format image, you can change this line to
"image name.jpg"
You can change the rectangle colour and size by changing the value in
this line
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
Change value in "(0, 0, 255)" to change
colour. Use-value between 0 and 255
For example :
- (0, 0, 255) red colour
- (0, 255, 0) green colour
- (255, 0, 0) blue colour
- (0, 255, 255) yellow colour
Now change this value ", 6)" to
change the size of the rectangle
awesome!! Now you learn Face Detection using OpenCV and Python
Enjoy ;) have a great day.
0 Comments