Open In App

Detect Cat Faces in Real-Time using Python-OpenCV

Last Updated : 13 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Face Detection is a technology used to identify faces in images. We can implement it using Python's OpenCV which provides pre-trained haar classifiers for detecting faces in animals such as the haarcascade_frontalcatface.xml and haarcascade_frontalcatface_extended.xml files in the haar cascades directory. In this article we will try detecting cats in images.

1. Importing Libraries

We import the OpenCV and Matplotlib libraries to handle image processing and visualization.

Python
import cv2
import numpy as np
import matplotlib.pyplot as plt

2. Loading Haar Cascade Classifiers

We load pre-trained Haar Cascade XML files for detecting faces and eyes. You can download it from here.

Python
cat_cascade = cv2.CascadeClassifier('/content/haarcascade_frontalcatface.xml')

3. Defining a Function for Face Detection

We will define a function to detect the cat's face in an image. Faces in the image are detected and marked with with rectangles. We can also adjust the min.Neighbour parameter which stands for minimum neighbors.

Python
def detect_cats(img):
    cat_img = img.copy()
    cat_rect = cat_cascade.detectMultiScale(cat_img, scaleFactor=1.2, minNeighbors=2)

    for (x, y, w, h) in car_rect:
        cv2.rectangle(cat_img, (x, y), (x + w, y + h), (255, 255, 255), 10)

    return cat_img

4. Converting to BGR to RGB

The BGR image is converted to RGB for detection.

Python
img = cv2.imread('/content/cat.webp')
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

Output:

cat
Cat

5. Displaying the Image with Detected Face

We visualize the image with rectangles drawn around detected faces.

Python
img = cv2.imread('/content/cat.webp')
img_copy1 = img.copy()

cats = detect_cats(img_copy1)
plt.imshow(cv2.cvtColor(cats, cv2.COLOR_BGR2RGB))
plt.show()

Output:

detect_cat
Detected Cat

We acn see that our model is able to detect cat in image.


Next Article
Article Tags :
Practice Tags :

Similar Reads