Open In App

Measure Size of an Object Using Python OpenCV

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about how to measure the size of an object using OpenCV which is implemented in Python. It is implemented by finding the contours around it. This can be done by first loading an image of an object, converting it to grayscale, and applying a threshold to separate the object from the background. It then finds the object’s contours in the thresholded image and draws them on the original image. The code calculates the area of the object in pixels using the cv2.contourArea() function and converts the area to a real-world unit of measurement using a scale factor. Finally, it prints the size of the object in the chosen unit of measurement.

Measure Size of an Object using Python OpenCV

Let’s see a few examples to measure the size of an object using Python’s openCV module.

Example 1: Measure the size of a Single Object in Python

GeeksforGeeks logo


Python3




import cv2
  
# Load the image
img = cv2.imread('/content/sample1.jpeg')
  
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
#to separate the object from the background
ret, thresh = cv2.threshold(gray, 127, 255, 0)
  
# Find the contours of the object 
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  
# Draw the contours on the original image
cv2.drawContours(img, contours, -1, (0,255,0), 3)
  
# Get the area of the object in pixels
area = cv2.contourArea(contours[0])
  
# Convert the area from pixels to a real-world unit of measurement (e.g. cm^2)
scale_factor = 0.1 # 1 pixel = 0.1 cm
size = area * scale_factor ** 2
  
# Print the size of the object
print('Size:', size)
  
# Display the image with the contours drawn
cv2.imwrite('Object.jpeg', img)
cv2.waitKey(0)
  
# Save the image with the contours drawn to a file
cv2.imwrite('object_with_contours.jpg', img)


Output:

First we will use the cv2.imread() function to load the image into a numpy array then convert the image to grayscale using the cv2.cvtColor() function. Apply a threshold to the grayscale image to separate the object from the background. The threshold can be applied using the cv2.threshold() function.

To find and draw the contours of the object in the thresholded image, we will use the cv2.findContours() function and cv2.drawContours() function respectively. Use the cv2.contourArea() function to calculate the area of the object in pixels. And at last, display the image with the contours drawn using the cv2.imshow() function and wait for a key press using the cv2.waitKey() function. Optionally, save the image to a file using the cv2.imwrite() function.

Size: 85.81500000000001

Output image

Example 2: Measure the size of Multiple Objects in Python

New, let us see and example to measure the size multiple objects.

Image with multiple objects

Python3




import cv2
import numpy as np
  
# Load the image
img = cv2.imread('path/to/image.jpg')
  
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
# Apply a threshold to the image to
# separate the objects from the background
ret, thresh = cv2.threshold(
    gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
  
# Find the contours of the objects in the image
contours, hierarchy = cv2.findContours(
    thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  
# Loop through the contours and calculate the area of each object
for cnt in contours:
    area = cv2.contourArea(cnt)
  
    # Draw a bounding box around each
    # object and display the area on the image
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
    cv2.putText(img, str(area), (x, y),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  
# Show the final image with the bounding boxes
# and areas of the objects overlaid on top
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
  
# Code By SR.Dhanush


Output:

Size of multiple objects



Similar Reads

Measure similarity between images using Python-OpenCV
Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let's find out which data image is more similar to the test image using python and OpenCV library in Python.Let's first load the image and find out the histogram of images.Importing library import cv2 Importing image data image = cv2.imread('test.jpg') Converting to gray
2 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 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
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
Measure The Time You Take To Type A Word Using Python
Here, we have task to measure the time takes to type a word in Python. In this article we will see how to measure the time you to type a word in Python, we will type the word and measure the type using some simple generally used methods. Example : Input : Type the word 'GeeksforGeeks': GeeksforGeeks Output: Time taken: 3.04 seconds Typing speed: 25
3 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 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. Module neededOpenCv: OpenCv is an open-source library that is useful for computer vision applications such as image processing, video processing, facial recognition, and detection, etc.Numpy: Numpy is a python package for scientific computing. It is
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
Practice Tags :