Vous êtes sur la page 1sur 1

import cv2

# Load the image


image = cv2.imread('Recs.jpg')

# Convert the image to grayscale


gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Check if grayscale conversion was successful


if gray is None:
print("Error converting to grayscale.")

# Find contours in the image


contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)

# Initialize a list to store the dimensions of all rectangles


rectangle_dimensions = []

# Iterate through the contours


for contour in contours:
# Approximate the contour with a polygon
approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)

# Check if the polygon has 4 vertices (i.e., it's a rectangle)


if len(approx) == 4:
# Sort the vertices in counter-clockwise order
approx = approx.reshape((4, 2))
approx = approx[approx[:, 0].argsort(), :]
approx = approx[approx[:, 0].argsort()[::-1], :]

# Calculate the width and height of the rectangle


width = int(cv2.norm(approx[0] - approx[1]))
height = int(cv2.norm(approx[0] - approx[3]))

# Add the dimensions to the list


rectangle_dimensions.append((width, height))

# Display the dimensions of all rectangles on the image


for i, (width, height) in enumerate(rectangle_dimensions):
cv2.putText(image, f'Rectangle {i+1} - Width: {width} Height: {height}', (10,
50 + i * 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 0, 225), 2)

# Display the image


cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Vous aimerez peut-être aussi