Detect an object with OpenCV-Python

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. This article focuses on detecting objects.

Note: For more information, refer to Introduction to OpenCV.

Object Detection

Object Detection is a computer technology related to computer vision, image processing, and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades.

Haar Cascades

Haar Cascade classifiers are an effective way for object detection. This method was proposed by Paul Viola and Michael Jones in their paper Rapid Object Detection using a Boosted Cascade of Simple Features. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.

  • Positive images – These images contain the images that we want our classifier to identify.
  • Negative Images – Images of everything else, which do not contain the object we want to detect.

Steps to download the requirements below

  • Run The following command in the terminal to install opencv.
    pip install opencv-python
  • Run the following command to in the terminal install the Matplotlib.
    pip install matplotlib
  • To download the haar cascade file and image used in the below code as a zip file click here.

Note: Put the XML file and the PNG image in the same folder as your Python script.

Implementation

Image used

python-opencv-detect-image

Opening an image

Python
import cv2
from matplotlib import pyplot as plt
  
  
# Opening image
img = cv2.imread("image.jpg")
  
# OpenCV opens images as BRG 
# but we want it as RGB and 
# we also need a grayscale 
# version
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  
# Creates the environment 
# of the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()

Output:

detect-object-python-opencv

Recognition

We will use the detectMultiScale() function of OpenCV to recognize big signs as well as small ones:

Python
# Use minSize because for not 
# bothering with extra-small 
# dots that would look like STOP signs
stop_data = cv2.CascadeClassifier('stop_data.xml')
found = stop_data.detectMultiScale(img_gray, 
                                   minSize =(20, 20))
# Don't do anything if there's 
# no sign
amount_found = len(found)
  
  
if amount_found != 0:
      
    # There may be more than one
    # sign in the image
    for (x, y, width, height) in found:
          
        # We draw a green rectangle around
        # every recognized sign
        cv2.rectangle(img_rgb, (x, y), 
                      (x + height, y + width), 
                      (0, 255, 0), 5)

Here is the full script for lazy devs:

Python
import cv2
from matplotlib import pyplot as plt
  
# Opening image
img = cv2.imread("image.jpg")
  
# OpenCV opens images as BRG 
# but we want it as RGB We'll 
# also need a grayscale version
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  
  
# Use minSize because for not 
# bothering with extra-small 
# dots that would look like STOP signs
stop_data = cv2.CascadeClassifier('stop_data.xml')
  
found = stop_data.detectMultiScale(img_gray, 
                                   minSize =(20, 20))
  
# Don't do anything if there's 
# no sign
amount_found = len(found)
  
if amount_found != 0:
      
    # There may be more than one
    # sign in the image
    for (x, y, width, height) in found:
          
        # We draw a green rectangle around
        # every recognized sign
        cv2.rectangle(img_rgb, (x, y), 
                      (x + height, y + width), 
                      (0, 255, 0), 5)
          
# Creates the environment of 
# the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()

Output :

python-opencv-detect-image

Detect an object with OpenCV-Python – FAQs

How to Detect Objects Using OpenCV Python

Object detection using OpenCV in Python can be performed using several methods, with one of the most common being the use of the Haar Cascade Classifier. This method involves using pre-trained classifiers for detecting objects like faces, eyes, or vehicles.

Steps to Detect Objects with Haar Cascade Classifier:

  1. Import Necessary Libraries: You need to import OpenCV.
import cv2
  1. Load Pre-trained Classifier: OpenCV provides several pre-trained classifiers, which can be loaded using cv2.CascadeClassifier.
# Load a pre-trained face detector classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
  1. Read the Image: Load the image where you want to detect objects.
image = cv2.imread('path_to_image.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale
  1. Detect Objects: Use the classifier to detect objects in the image.
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)
  1. Draw Rectangles Around Detected Objects: For each detected object, draw a rectangle around it.
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
  1. Display the Result:
cv2.imshow('Detected Faces', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

How to Use OpenCV to Detect Objects in Image and Track Them Over Time

For tracking objects over time in video streams or video files, you can use the combination of object detection (using methods like the Haar Cascade) followed by object tracking algorithms provided by OpenCV, such as KCF, TLD, or MIL.

  1. Detect the Object in the First Frame: Use any object detection method to locate the object in the first frame.
  2. Initialize the Tracker: Once the object is detected, initialize a tracker with the object’s position.
  3. Update Tracker for Each New Frame: For each new frame in the video, update the tracker to find the object’s new position.
# Initialize tracker
tracker = cv2.TrackerKCF_create()
init_box = None # Assuming init_box is the bounding box of detected object
video = cv2.VideoCapture('video_path.mp4')

# Read first frame
ok, frame = video.read()
if ok:
init_box = cv2.selectROI(frame, False) # Let user select ROI
tracker.init(frame, init_box)

while True:
ok, frame = video.read()
if not ok:
break

ok, bbox = tracker.update(frame)
if ok:
(x, y, w, h) = [int(v) for v in bbox]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Tracking failure", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

cv2.imshow("Tracking", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

video.release()
cv2.destroyAllWindows()

How Do You Count the Number of Objects in an Image Using OpenCV Python?

To count the number of objects in an image using OpenCV, you can follow the detection steps and simply count the number of detected instances.

  1. Detect Objects: As shown previously with the Haar Cascade or any other detection method.
  2. Count: The length of the list of detections gives the count of objects.
# Continuing from the face detection example
num_faces = len(faces)
print(f"Number of faces detected: {num_faces}")

These methods and steps provide a robust framework for incorporating object detection and tracking functionalities in your applications using Python and OpenCV



    Previous Article
    Next Article

    Similar Reads

    Python | Detect corner of an image using OpenCV
    OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
    2 min read
    How to Detect Shapes in Images in Python using OpenCV?
    Prerequisites: OpenCV OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function
    3 min read
    Detect Cat Faces in Real-Time using Python-OpenCV
    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 p
    2 min read
    OpenCV Python: How to detect if a window is closed?
    OpenCV in Python provides a method cv2.getWindowProperty() to detect whether a window is closed or open. getWindowProperty() returns -1 if all windows are closed. This is one of the main problems we face while using the OpenCV package, sometimes it's hard to detect whether the window is open or closed. when a user closes the window the method detec
    2 min read
    Detect and Read Barcodes with OpenCV in Python
    A barcode is a graphical representation of data that is machine-readable. It consists of parallel lines or rectangles of varying widths and spacings, along with specific patterns, that encode information. Barcodes are widely used for automatic identification and tracking of products, assets, inventory, and more. In this article, we will see how we
    3 min read
    Detect the RGB color from a webcam using Python - OpenCV
    Prerequisites: Python NumPy, Python OpenCV Every image is represented by 3 colors that are Red, Green and Blue. Let us see how to find the most dominant color captured by the webcam using Python. Approach: Import the cv2 and NumPy modulesCapture the webcam video using the cv2.VideoCapture(0) method.Display the current frame using the cv2.imshow() m
    2 min read
    How to detect a Christmas Tree using Opencv
    Detecting objects in images is a powerful application of computer vision, and OpenCV provides an extensive library for handling these tasks. Christmas trees are typically green and have a triangular shape, making them identifiable through image processing techniques. In this article, we will guide you through detecting a Christmas tree in an image.
    7 min read
    OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
    Content has been removed on Author's request.
    1 min read
    Transition from OpenCV 2 to OpenCV 3.x
    OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
    2 min read
    Top Books for Learning OpenCV: Computer Vision with OpenCV Library
    OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
    5 min read
    Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
    An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
    6 min read
    What is the difference between Object Localization, Object Recognition, and Object Detection?
    Object localization, object recognition, and object detection are closely related concepts in the context of further computer vision development, covering various visual data analysis aspects. In this article, we are going to explore object localization, object recognition, and object detection. Table of Content What is Object Localization?What is
    7 min read
    Python OpenCV: Object Tracking using Homography
    In this article, we are trying to track an object in the video with the image already given in it. We can also track the object in the image. Before seeing object tracking using homography let us know some basics. What is Homography? Homography is a transformation that maps the points in one point to the corresponding point in another image. The ho
    4 min read
    Count number of Object using Python-OpenCV
    In this article, we will use image processing to count the number of Objects using OpenCV in Python. Google Colab link: https://colab.research.google.com/drive/10lVjcFhdy5LVJxtSoz18WywM92FQAOSV?usp=sharing Module neededOpenCv: OpenCv is an open-source library that is useful for computer vision applications such as image processing, video processing
    3 min read
    Real time object color detection using OpenCV
    In this article, we will discuss how to detect a monochromatic colour object using python and OpenCV. Monochromatic color means light of a single wavelength. We will use the video, captured using a webcam as input and try to detect objects of a single color, especially Blue. But you can detect any color if you set the range properly, we'll discuss
    4 min read
    Region Proposal Object Detection with OpenCV, Keras, and TensorFlow
    In this article, we'll learn how to implement Region proposal object detection with OpenCV, Keras and TensorFlow. Install all the dependencies Use the pip command for installing all the dependencies pip install tensorflow keras imutils pip install opencv-contrib-python Note: Make sure about installing the above OpenCV package otherwise you might fa
    9 min read
    OpenCV Selective Search For Object Detection
    OpenCV is a Python library that is used to study images and video streams. It basically extracts the pixels from the images and videos (stream of image) so as to study the objects and thus obtain what they contain. It contains low-level image processing and high-level algorithms for object detection, feature matching etc. In this article, we will d
    14 min read
    Getting Started With Object Tracking Using OpenCV
    OpenCV, developed by Intel in the early 2000s, is a popular open-source computer vision library used for real-time tasks. It offers various features like image processing, face detection, object detection, and more. In this article, we explore object-tracking algorithms and how to implement them using OpenCV and Python to track objects in videos. G
    4 min read
    Object Detection with YOLO and OpenCV
    Object Detection is a task of computer vision that helps to detect the objects in the image or video frame. It helps to recognize objects count the occurrences of them to keep records, etc. The objective of object detection is to identify and annotate each of the objects present in the media. YOLO(You Only Look Once) is a state-of-the-art model to
    6 min read
    Detect and Remove the Outliers using Python
    Outliers, deviating significantly from the norm, can distort measures of central tendency and affect statistical analyses. The piece explores common causes of outliers, from errors to intentional introduction, and highlights their relevance in outlier mining during data analysis. The article delves into the significance of outliers in data analysis
    10 min read
    Detect and Recognize Car License Plate from a video in real time
    Recognizing a Car License Plate is a very important task for a camera surveillance-based security system. We can extract the license plate from an image using some computer vision techniques and then we can use Optical Character Recognition to recognize the license number. Here I will guide you through the whole procedure of this task.Requirements:
    11 min read
    How to detect Deepfakes using AI?
    With the rapid advancements in artificial intelligence, deep fakes—synthetically generated media in which a person's likeness is manipulated—have become increasingly sophisticated. These realistic forgeries can deceive even the most discerning eye, posing significant risks to privacy, security, and public trust. Detecting deep fakes is crucial to m
    9 min read
    Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
    Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
    5 min read
    Addition and Blending of images using OpenCV in Python
    When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
    2 min read
    Python | Play a video in reverse mode using OpenCV
    OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV's application areas include : 1) Facial recognition system 2) motion tracking 3) Artificial neural network 4) Deep neural network 5) video streaming etc. In Python, one can use an OpenCV library named C
    3 min read
    Opening multiple color windows to capture using OpenCV in Python
    OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
    2 min read
    Converting Color video to grayscale using OpenCV in Python
    OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted usi
    1 min read
    Image Pyramid using OpenCV | Python
    Image Pyramids are one of the most beautiful concept of image processing.Normally, we work with images with default resolution but many times we need to change the resolution (lower it) or resize the original image in that case image pyramids comes handy. The pyrUp() function increases the size to double of its original size and pyrDown() function
    1 min read
    Face Detection using Python and OpenCV with webcam
    OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
    4 min read
    Python | OpenCV BGR color palette with trackbars
    OpenCV is a library of programming functions mainly aimed at real-time computer vision. In this article, Let's create a window which will contain RGB color palette with track bars. By moving the trackbars the value of RGB Colors will change b/w 0 to 255. So using the same, we can find the color with its RGB values. Libraries needed: OpenCV Numpy Ap
    2 min read
    Article Tags :
    three90RightbarBannerImg