Open In App

Detect an object with OpenCV-Python

Last Updated : 10 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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



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
Python | Detect Polygons in an Image using OpenCV
Approach : The approach we would be used to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has. For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle
2 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
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
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
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