Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find height and width for each individual contour on an image using OpenCV

img link

In the above image, if the entire width is specified say 30'5". How do I calculate height and width for each individual contour on that image using opencv

like image 853
user1027130 Avatar asked Feb 10 '20 11:02

user1027130


People also ask

What is a contour in OpenCV?

Typically, a specific contour refers to boundary pixels that have the same color and intensity. OpenCV makes it really easy to find and draw contours in images. It provides two simple functions: Also, it has two different algorithms for contour detection: We will cover these in detail, in the examples below.

How to get the width of an image in OpenCV?

The width of the image is stored at index 1. The number of channels in the image is stored at index 2. Given below are the examples of OpenCV Get Image Size: OpenCV program in python determines the dimension of a given image and displays the height, width, and number of channels in the given image as the output on the screen.

How do I get the height and width of a contour?

To obtain the height and width of a contour, you can use cv2.boundingRect. The function returns the contour information in the form of x,y,w,h. The height for a specific contour will be h and the width will be w. Here's the result with the w in pixels drawn onto the image.

How to identify the contours of an image?

Let’s consider such an example too. When the objects in an image are strongly contrasted against their background, you can clearly identify the contours associated with each object. But what if you have an image, like Figure 16 below.


Video Answer


1 Answers

To obtain the height and width of a contour, you can use cv2.boundingRect. The function returns the contour information in the form of x,y,w,h. The height for a specific contour will be h and the width will be w. Here's the result with the w in pixels drawn onto the image.

enter image description here

import cv2

# Load image, convert to grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find contours, obtain bounding rect, and draw width
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    cv2.putText(image, str(w), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
    cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 1)

cv2.imshow('image', image)
cv2.waitKey()
like image 126
nathancy Avatar answered Sep 20 '22 00:09

nathancy