Face Detection using Opencv
Welcome back to a amazing Blog on Opencv Face detection .
In this blog you learn how you can detect faces from images.
Requirements.
- Opencv (pip install opencv-python)
- numpy (automatically install with opencv)
- python 3.x
So lets code first for Face detection form image.
# Opencv - Dynamic Coding
# Face-Detection from Images.
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, 1)
# Draw rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
# Display the output
cv2.imshow('img', img)
cv2.waitKey()
Output.
As you can see the Code detects the face from image and draw a rectangle over it.
How It works.
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
This file is easily found on OpenCv github profile and this file contain all the data requires to detect the faces from the images as well as videos.
Download harrcascade_frontalface_default.xml .from here 👈👈
# Read the input image
img = cv2.imread('test.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
The answer is detecting faces in greyscale image is easy and fast if compared to colorful images because in grayscale image the detector only have to detect only black and white color and one more thing is the XML file only for grayscale image.
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 1)
# Draw rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
1. Grayscale image
2. Scale factor
3. Minimum neighbors.
4. Minimum size ( optional)
scaleFactor: The value indicates how much the image size is reduced at each image scale. A lower value uses a smaller step for downscaling. This allows the algorithm to detect the face. It has a value of x.y, where x and y are arbitrary values you can set.
minNeighbors: This parameter specifies how many “neighbors” each candidate rectangle should have. A higher value results in less detections but it detects higher quality in an image. You can use a value of X that specifies a finite number.
minSize: The minimum object size. By default it is (30,30). The smaller the face in the image, it is best to adjust the minSize value lower.
# Display the output
cv2.imshow('img', img)
cv2.waitKey()
Thank you ..
If have Any doubts and Errors , comment section is open for you and we will try to solve your doubts as soon as possible.
No comments