Adventures in Machine Learning

Counting Objects in an Image: A Step-by-Step Python Guide

Counting Objects in an Image

Images are widely used in today’s world to capture moments, communicate ideas, and even solve problems. One such problem that can be solved using images is counting objects.

Counting objects in an image can be useful for various reasons, such as counting the number of people in a crowd, the number of cars on a road, or the number of animals in a wildlife reserve. In this article, we will learn how to count objects in an image using Python and the cvlib library.

Importing Required Libraries

Before we start counting objects in an image, we need to import the required libraries. In this case, we will be using the cvlib library, which is a high-level library for computer vision tasks built on top of OpenCV.

OpenCV is a popular open-source library for computer vision tasks that provides a wide range of functions for image processing, machine learning, and deep learning.

Loading and Viewing the Image

Once we have imported the required libraries, we can load and view the image we want to count the objects in. We can do this using the imread function from the OpenCV library and the imshow function from the matplotlib library.

The imread function reads the image from the file, and the imshow function displays the image on the screen.

Creating Boxes around various Objects

To count objects in an image, we first need to detect the objects in the image and draw bounding boxes around them. We can do this using the detect_common_objects function from the cvlib library and the draw_bbox function from the OpenCV library.

The detect_common_objects function detects common objects in the image and returns the bounding boxes and labels for each object. The draw_bbox function draws the bounding box around the object and labels it with the corresponding label.

Counting Objects in the Image

Once we have drawn the bounding boxes around the objects in the image, we can count the number of objects in the image. We can do this by simply counting the number of labels in the image.

We can use the len function to count the labels in the image.

Sample Output

Let’s take an example to see how we can count objects in an image. Consider the image below, which shows two dogs playing in a park.

![dogs playing in a park](https://github.com/arunponnusamy/cvlib/raw/master/examples/images/dog.jpg)

To count the number of dogs in this image, we can use the following code:

“`

import cv2

import matplotlib.pyplot as plt

import cvlib as cv

# Read the image

image = cv2.imread(‘dog.jpg’)

# Detect objects in the image

bbox, label, conf = cv.detect_common_objects(image)

# Draw bounding boxes around the objects

output_image = cv.object_detection.draw_bbox(image, bbox, label, conf)

# Count the number of dogs

num_dogs = len([l for l in label if l == ‘dog’])

# Display the output image with the boxes and count

plt.imshow(output_image)

plt.title(‘Detected objects’)

plt.axis(‘off’)

plt.show()

print(f’Number of dogs detected: {num_dogs}’)

“`

The above code will output the following:

![dogs detected](https://imgur.com/V42wbuL.png)

Number of dogs detected: 2

As we can see from the output, the code has successfully detected the two dogs in the image and counted them.

Conclusion

In this article, we learned how to count objects in an image using Python and the cvlib library. We first imported the required libraries, loaded and viewed the image, created bounding boxes around the objects in the image, and finally counted the number of objects in the image.

We also saw a sample output of how to count the number of dogs in an image. Counting objects in an image can be a useful task in many different applications.

With just a few lines of Python code, we can detect and count objects in an image. In this article, we have discussed how to count objects in an image using Python and the cvlib library.

We first imported the required libraries, loaded and viewed the image, created bounding boxes around the objects in the image, and finally counted the number of objects in the image. In this expansion, we will dive deeper into the concepts discussed in the original article and extend our understanding of how we can count objects in an image.

Try it with some random images

Now that we know how to count objects in an image, let’s try it out with some random images. To start with, let’s download some random images from the internet.

We can use the BeautifulSoup library to scrape images from a website. We can then use the requests library to download these images.

Here’s the code to do so:

“`

from bs4 import BeautifulSoup

import requests

import shutil

url = ‘https://unsplash.com/s/photos/’

search_term = ‘dogs’

response = requests.get(url + search_term)

soup = BeautifulSoup(response.content, ‘html.parser’)

for i, img in enumerate(soup.find_all(‘img’)):

img_url = img.attrs.get(‘src’)

response = requests.get(img_url, stream=True)

with open(f'{search_term}_{i}.jpg’, ‘wb’) as out_file:

shutil.copyfileobj(response.raw, out_file)

del response

print(f’Downloaded {search_term}_{i}.jpg’)

“`

The above code will download 10 images of dogs from the Unsplash website and save them to our local directory. Alternatively, we can also use the imread function from the OpenCV library to load a random image from our local directory.

“`

import cv2

import matplotlib.pyplot as plt

import cvlib as cv

# Read the image

image = cv2.imread(‘dogs_0.jpg’)

# Detect objects in the image

bbox, label, conf = cv.detect_common_objects(image)

# Draw bounding boxes around the objects

output_image = cv.object_detection.draw_bbox(image, bbox, label, conf)

# Count the number of dogs

num_dogs = len([l for l in label if l == ‘dog’])

# Display the output image with the boxes and count

plt.imshow(output_image)

plt.title(‘Detected objects’)

plt.axis(‘off’)

plt.show()

print(f’Number of dogs detected: {num_dogs}’)

“`

The code will output the following:

“`

Number of dogs detected: 1

“`

As we can see from the output, the code has successfully detected one dog in the image.

Understanding the Code in Detail

Now that we have seen how to count objects in an image using Python and the cvlib library with some sample code, let’s dive into the details of how the code works.

Importing Required Libraries

We first imported the required libraries. We used the cvlib library and OpenCV library for object detection and image processing.

We also used the matplotlib library to display the output image.

Loading and Viewing the Image

We then loaded and viewed the image using the imread and imshow functions, respectively. The imread function reads the image from a file, and the imshow displays the image on the screen.

Creating Boxes around various Objects

We then used the detect_common_objects function from the cvlib library to detect objects in the image and return their bounding boxes and labels. We also used the draw_bbox function from the OpenCV library to draw the bounding box around the objects and label it with the corresponding label.

Counting Objects in the Image

Once we have drawn the bounding boxes around the objects in the image, we can count the number of objects in the image by simply counting the number of labels in the image. We used the len function to count the number of labels in the image.

Conclusion

In this expansion, we have taken a deeper look at how to count objects in an image using Python and the cvlib library. We have discussed how to download random images from the internet, load them into Python, detect objects in the image, and count the number of objects.

We hope this expansion has been helpful in extending your understanding of how to count objects in an image. In summary, this article has highlighted how to count objects in an image using Python and the cvlib library.

We have discussed the importance of counting objects in an image for various applications and have provided a step-by-step guide to detecting and counting objects in an image. We have also demonstrated the same using randomly downloaded images.

Understanding how to count objects in an image can be useful for a wide range of tasks and applications, including object recognition in autonomous vehicles, detecting defects in manufacturing, and identifying objects in medical images. It is a vital skillset for computer vision in today’s digital era.

With the simple and straightforward steps shared in this article, readers can easily grasp the basics of object detection and counting. The takeaway from this article is that with these skills, one can automate and extract information from images that would be time-consuming or difficult to do manually.

Popular Posts