Lab Program 12
Lab Program 12
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.
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()
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