12) Write a program to detect a face/s in an image.
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
image = cv2.imread('images.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_image,
scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Detected Faces', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
Import the cv2 module.
face_cascade =
cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
• The Haar cascade classifier for face detection is
loaded.
• This classifier is a pre-trained model that can detect
frontal faces in images.
image = cv2.imread('images.jpg')
• imread() function loads an image from the specified file
and returns it.
gray_image = cv2.cvtColor(image,
cv2.COLOR_BGR2GRAY)
The image is converted to grayscale using above function.
faces = face_cascade.detectMultiScale(gray_image,
scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
• The face_cascade.detectMultiScale function is used
to detect faces in the grayscale image.
• The parameters scaleFactor=1.1, minNeighbors=5,
and minSize=(30,30) control the detection process
• detectMultiScale function returns position of
detected faces as rectangles
1. scaleFactor: Specifies the scale factor used to resize the
input image for different scales.
2. minNeighbors: Specifies the minimum number of
neighboring rectangles that should overlap to consider
a face detection as valid.
3. minSize : Specifies the minimum size of the face to be
detected.
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
• faces contains rectangle coordinates corresponding to
detected faces. i.e (x,y,w,h)
• If 3 faces are detected, then faces contains coordinates of
3 rectangles.
image : On which rectangle has to be drawn
(x,y) : Coordinate of top left corner of rectangle
(x+w,y+h): Coordinate of bottom right corner of rectangle
(0,255,0) : Color of rectangle
2 : Thickness of line used for drawing rectangle
cv2.imshow('Detected Faces', image)
• cv2.imshow() method is used to display an image in a
window.
cv2.waitKey(0)
cv2.destroyAllWindows()
waitKey()
• waitKey() function of Python OpenCV allows users to
display a window for given milliseconds or until any
key is pressed.
• If 0 is passed in the argument it waits till any key is
pressed.
cv2.waitKey(0)
cv2.destroyAllWindows()
• The function cv2.destroyAllWindows() is used in
OpenCV (cv2) to close all the OpenCV windows that
were created with cv2.imshow().
Output Input Image
Output Image