Python OpenCV Object Detection Tutorial

OpenCV is a comprehensive and freely accessible library utilized for image processing, machine learning, and computer vision. It also contributes significantly to real-time applications. By leveraging the OpenCV library, we can efficiently analyze both images and videos to detect objects, recognize faces, or even interpret human handwriting present within the content. This tutorial will concentrate specifically on object detection within images using OpenCV. We will explore how to implement object detection from a specified image through a Python program utilizing OpenCV.

Object Detection

In essence, object detection represents a contemporary computational technology that intersects with image processing, deep learning, and computer vision to identify objects located within an image file. The various technologies employed in the object detection methodology (as previously noted) focus on recognizing instances of objects within both images and videos.

Object Detection using OpenCV

In the preceding section, we explored the concept of object detection. Now, we will delve into how to execute object detection on images or videos utilizing the OpenCV library. Initially, we will import the OpenCV library within our Python script, followed by employing specific functions to carry out object detection on a provided image file. However, prior to importing and utilizing these functions from the library, let’s first ensure that we have installed the necessary requirements for implementing the object detection technique.

In this instructional guide, we will implement the Haar cascade method for the purpose of object detection. Before diving into the practical application, let's take a moment to briefly explore the fundamentals of the Haar cascade technique.

Haar cascade

Essentially, the Haar cascade method is a machine learning-based strategy that utilizes a vast number of both positive and negative images to train a classifier, enabling it to distinguish between different images. Haar cascade classifiers are regarded as an efficient means of performing object detection while using the OpenCV library. Let’s delve into the definitions of positive and negative images that we have previously mentioned:

  • Positive images: These images feature the objects that we aim to identify through the classifier.
  • Negative Images: These images lack any objects that we intend to detect with the classifier, and they may include images of anything else.
  • Requirements for object detection with Python OpenCV:

To begin with, it is essential to install several crucial libraries on our system, as they are necessary for executing object detection tasks. The following libraries must be installed in our system to meet the requirements for conducting object detection:

1. Installation of OpenCV library:

To begin with, an essential prerequisite for conducting object detection with the OpenCV library is that the library must be installed on your device. This allows us to import it into a Python script and utilize its functions for object detection. In the event that this library is absent from your system, you can install it by executing the following command in your command prompt terminal:

Example

pip install opencv-python

Upon pressing the enter key after inputting this command in the terminal, the pip installer within the command prompt will initiate the installation of the OpenCV library onto our system.

It is evident that the OpenCV library has been installed successfully on our system. We can now proceed to import it into a Python script to utilize its various functions.

2. Installation of matplotlib library:

Matplotlib serves as a valuable tool for actions such as opening, closing, and reading images within a Python application. Therefore, installing this library is essential for tasks related to object detection. In the event that the matplotlib library is not installed on your system, you can utilize the following command in your command prompt terminal to set it up:

Example

pip install matplotlib

Upon pressing the enter key following the input of this command in the terminal, the pip installer within the command prompt will initiate the installation process into our system.

It is evident that the matplotlib library has been correctly installed on our system. We can now proceed to import it into a Python script, allowing us to utilize its capabilities for tasks such as opening, reading, and manipulating images.

All necessary libraries for conducting object detection have been successfully installed, and we are now ready to proceed with the implementation phase of this task.

Implementation of Object detection in Python:

In this section, we will develop Python programs aimed at executing object detection and explore its implementation. To facilitate this, we will utilize the subsequent image within our Python program to carry out the object detection process on it:

Opening the Image

To begin, we will open the image displayed above and establish the environment depicted in the picture for the output. Initially, let’s examine an example program to grasp the implementation, and afterwards, we will delve into the explanation section.

Illustration 1: Utilizing OpenCV and the matplotlib library to open an image within a Python script:

Example

# Import OpenCV module

import cv2

# Import pyplot from matplotlib as pltd

from matplotlib import pyplot as pltd

# Opening the image from files

imaging = cv2.imread("opencv-od.png")

# Altering properties of image with cv2

img_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)

imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)

# Plotting image with subplot() from plt

pltd.subplot(1, 1, 1)

# Displaying image in the output

pltd.imshow(imaging_rgb)

pltd.show()

Output:

Explanation:

Initially, we imported the OpenCV library (aliased as cv2) along with the matplotlib library (aliased as plt) into our program to leverage their functionalities within the code. Subsequently, we utilized the imread function from the cv2 module to open the image file.

Subsequently, we established the attributes for the image that we loaded into the application utilizing the cv2 functions. After that, we arranged the image using the subplot function from the plt module, providing the necessary parameters within it. Finally, we employed the imshow and show functions of the plt library to display the image in the output.

The output illustrates that the image is rendered as a consequence of the program's execution, with its edges being represented in a sub-plot format.

Recognition or object detection in the image

Next, we will implement the detectMultiScale function within our program to identify the objects contained in the image. Below is the syntax for utilizing the detectMultiScale method in the code:

Example

found = xml_data.detectMultiScale(img_gray,

                                   minSize = (30, 30))

In this program, we will incorporate a conditional statement within the function to determine whether any objects present in the image have been detected, and subsequently highlight the identified portions. To illustrate the process of object detection within an image, let’s examine an example program.

Example 2: Utilizing the detectMultiScale function for object detection within an image in the subsequent Python program:

Example

# Import OpenCV module

import cv2

# Import pyplot from matplotlib as plt

from matplotlib import pyplot as pltd

# Opening the image from files

imaging = cv2.imread("opencv-od.png")

# Altering properties of image with cv2

imaging_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)

imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)

# Importing Haar cascade classifier xml data

xml_data = cv2.CascadeClassifier('XML-data.xml')

# Detecting object in the image with Haar cascade classifier

detecting = xml_data.detectMultiScale(imaging_gray,

                                   minSize = (30, 30))

# Amount of object detected

amountDetecting = len(detecting)

# Using if condition to highlight the object detected

if amountDetecting != 0:

    for (a, b, width, height) in detecting:

        cv2.rectangle(imaging_rgb, (a, b), # Highlighting detected object with rectangle

                      (a + height, b + width),

                      (0, 275, 0), 9)

# Plotting image with subplot() from plt

pltd.subplot(1, 1, 1)

# Displaying image in the output

pltd.imshow(imaging_rgb)

pltd.show()

Output:

Explanation:

Upon launching the image within the application, we proceeded to incorporate the cascade classifier XML file into the program. Subsequently, we employed the detectMultiScale method alongside the imported cascade file to ascertain the presence of the object within the image.

In our program, we implemented an if statement to ascertain whether an object has been detected. Upon confirming the presence of the object, we utilized a for loop in conjunction with cv2 functions to emphasize the identified portion of the object. Following this enhancement of the detected object's area within the image, we presented the modified image using both the plt show and imshow functions.

Upon executing the program, we observe the output displaying the image with the section containing the detected object highlighted.

Input Required

This code uses input(). Please provide values below: