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
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.
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With