0% found this document useful (0 votes)
16 views2 pages

Dimension

The document contains Python code to detect rectangles in an image. It uses OpenCV functions like Canny edge detection, Hough line transform and contour detection to find rectangles. It first detects line segments, filters horizontal and vertical lines, and uses the remaining line segments to find rectangles. It then blurs the background of the image outside these rectangles. Finally, it analyzes contours in the blurred image to measure the width and height of each detected rectangle and displays these dimensions on the output image.

Uploaded by

Slimen Zeineb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Dimension

The document contains Python code to detect rectangles in an image. It uses OpenCV functions like Canny edge detection, Hough line transform and contour detection to find rectangles. It first detects line segments, filters horizontal and vertical lines, and uses the remaining line segments to find rectangles. It then blurs the background of the image outside these rectangles. Finally, it analyzes contours in the blurred image to measure the width and height of each detected rectangle and displays these dimensions on the output image.

Uploaded by

Slimen Zeineb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import cv2

import numpy as np

def detect_rectangles(image, low_threshold=10, high_threshold=20):


blurred = cv2.GaussianBlur(image, (5, 5), 0)
edges = cv2.Canny(blurred, low_threshold, high_threshold)
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=10,
maxLineGap=20)

rectangles = []
for line in lines:
x1, y1, x2, y2 = line[0]
if abs(y2 - y1) < 10: # filter horizontal lines
continue
slope = (y2 - y1) / (x2 - x1) if x1 != x2 else float('inf')
if abs(slope - 0) < 0.1 or abs(slope - np.inf) < 0.1: # filter horizontal
and vertical lines
continue

if x1 < image.shape[1] / 2:
rectangles.append((x1, y1, x2, y2))
else:
rectangles.append((x2, y2, x1, y1))

return rectangles

def blur_background(image, rectangles, ksize=(25, 25)):


mask = np.zeros(image.shape[:2], dtype=np.uint8)

for rect in rectangles:


x1, y1, x2, y2 = rect
cv2.rectangle(mask, (x1, y1), (x2, y2), 255, -1)

masked_image = cv2.bitwise_and(image, image, mask=mask)


blurred_background = cv2.GaussianBlur(masked_image, ksize, 0)
unmasked_image = cv2.bitwise_and(image, image, mask=cv2.bitwise_not(mask))
result = cv2.add(blurred_background, unmasked_image)

return result

image = cv2.imread('scie vertical.png')

rectangles = detect_rectangles(image, 10, 20)


blurred_image = blur_background(image, rectangles, ksize=(25, 25))

cv2.imwrite('output_image.jpg', blurred_image)

# Load the image


image = cv2.imread('output_image.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.001 * 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()

You might also like