To calculate an area using cv2.contourArea, you need to follow these steps:
Here is an example code snippet that demonstrates how to do this:
import cv2
# Read the image
img = cv2.imread('image.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply thresholding
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Find the contours
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Iterate over each contour and calculate its area
total_area = 0
for contour in contours:
area = cv2.contourArea(contour)
total_area += area
# Print the total area
print('Total area:', total_area)
This code first reads an image, converts it to grayscale, applies thresholding, and finds the contours. It then iterates over each contour and calculates its area using cv2.contourArea. Finally, it adds up the areas of all the contours to get the total area and prints it.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-01-21 11:00:00 +0000
Seen: 11 times
Last updated: Nov 07 '21