Skip to content
Related Articles

Related Articles

Detect Cat Faces in Real-Time using Python-OpenCV
  • Last Updated : 03 Jul, 2020

Face Detection is a technology to identify faces from the image. We use Python’s OpenCV for this. We can also use Face Detection in the case of Animals too. If one can take a close look at the OpenCV repository, the haar cascades directory to be specific (where the OpenCV stores all its pre-trained haar classifiers to detect various objects, body parts, etc.), there are two files:

  • haarcascade_frontalcatface.xml
  • haarcascade_frontalcatface_extended.xml

The objective of the program given is to detect the object of interest(cat face) in real-time and to keep tracking the same object. This is a simple example of how to detect the cat face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects.

Below is the implementation.





# OpenCV program to detect cat face in real time 
# import libraries of python OpenCV 
# where its functionality resides 
import cv2 
# load the required trained XML classifiers 
# data/haarcascades/haarcascade_frontalcatface.xml 
# Trained XML classifiers describes some features of some 
# object we want to detect a cascade function is trained 
# from a lot of positive(faces) and negative(non-faces) 
# images. 
face_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml'
# capture frames from a camera 
cap = cv2.VideoCapture(0
# loop runs if capturing has been initialized. 
while 1
    # reads frames from a camera 
    ret, img = 
    # convert to gray scale of each frames 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    # Detects faces of different sizes in the input image 
    faces = face_cascade.detectMultiScale(gray, 1.3, 5
    for (x,y,w,h) in faces: 
        # To draw a rectangle in a face 
        roi_gray = gray[y:y+h, x:x+w] 
        roi_color = img[y:y+h, x:x+w] 
    # Display an image in a window 
    # Wait for Esc key to stop 
    k = cv2.waitKey(30) & 0xff
    if k == 27
# Close the window 
# De-allocate any associated memory usage 




Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :