Learn how to identify and locate rectangles within an image using various techniques and visual cues.
This document outlines the steps to detect rectangles in an image using OpenCV, a popular Python library for computer vision. The process involves preprocessing the image, detecting edges, finding contours, filtering for rectangular shapes, and finally extracting the coordinates of the detected rectangles.
Preprocess the image:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
Detect edges:
edges = cv2.Canny(blurred, 50, 150)
Find contours:
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Filter contours for rectangles:
approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
if len(approx) == 4 and cv2.isContourConvex(approx):
Extract rectangle coordinates:
approx array.(Optional) Draw rectangles on the original image:
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) to draw rectangles on the original image, where (x1, y1) and (x2, y2) are the top-left and bottom-right corner coordinates of the detected rectangle.This Python code uses OpenCV to detect rectangles in an image. It preprocesses the image, detects edges, finds contours, filters them for potential rectangles based on aspect ratio, extracts rectangle coordinates, and optionally draws the rectangles on the original image.
import cv2
# Load the image
image = cv2.imread('image.jpg')
# 1. Preprocess the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 2. Detect edges
edges = cv2.Canny(blurred, 50, 150)
# 3. Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 4. Filter contours for rectangles
rectangles = []
for contour in contours:
    approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
    if len(approx) == 4 and cv2.isContourConvex(approx):
        # Calculate aspect ratio
        x, y, w, h = cv2.boundingRect(approx)
        aspect_ratio = float(w) / h
        # Define aspect ratio threshold for rectangles (adjust as needed)
        if 1.2 < aspect_ratio < 2.5:  
            rectangles.append(approx)
# 5. Extract rectangle coordinates
for rectangle in rectangles:
    x, y, w, h = cv2.boundingRect(rectangle)
    print(f"Rectangle coordinates: Top-left:({x}, {y}), Bottom-right:({x+w}, {y+h})")
# 6. (Optional) Draw rectangles on the original image
for rectangle in rectangles:
    x, y, w, h = cv2.boundingRect(rectangle)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the result
cv2.imshow('Detected Rectangles', image)
cv2.waitKey(0)
cv2.destroyAllWindows()Explanation:
Image Preprocessing:
Edge Detection:
Contour Finding:
cv2.RETR_EXTERNAL retrieves only the outermost contours.cv2.CHAIN_APPROX_SIMPLE simplifies the contour representation, saving memory.Rectangle Filtering:
cv2.approxPolyDP.Coordinate Extraction:
cv2.boundingRect.Drawing Rectangles (Optional):
To use the code:
'image.jpg' with the path to your image file.General Considerations:
GaussianBlur and Canny. These parameters might need adjustments depending on the specific image characteristics like resolution and noise levels.cv2.approxPolyDP can help reduce processing time.Possible Improvements:
cv2.minAreaRect function to get the angle of rotation and filter rectangles based on that.cv2.approxPolyDP.Applications:
This article outlines a step-by-step process for detecting rectangles within an image using OpenCV in Python.
1. Image Preprocessing:
2. Edge Detection:
3. Contour Detection:
4. Rectangle Filtering:
5. Coordinate Extraction:
6. Visualization (Optional):
This process effectively identifies and locates rectangular shapes within images, providing a foundation for various applications like object detection and image analysis.
This article provides a comprehensive guide to detecting rectangles in images using OpenCV and Python. By understanding and implementing these steps, developers can effectively identify and extract rectangular shapes for various applications. The process involves preprocessing the image, detecting edges, finding contours, filtering for rectangular shapes based on specific criteria, and finally extracting the coordinates of the detected rectangles. This technique proves valuable in diverse fields, including object detection, document analysis, and robotics, showcasing its versatility and significance in computer vision tasks. However, it's important to note that the effectiveness of this method depends on factors like image quality, background complexity, and parameter tuning. Further exploration and adaptation of these techniques can lead to more robust and accurate rectangle detection in real-world scenarios.
 How to detect a rectangle using OpenCV code in Python - Quora | Feb 3, 2023 ... Find Contours in the image ( image should be binary as given in your question) · First, check number of elements in the approximated contours of ...
 How to detect a rectangle and square in an image using OpenCV ... | How to detect a rectangle and square in an image using OpenCV Python - To detect a rectangle and square in an image, we first detect all the contours in the image. Then Loop over all contours. Find the approximate contour for each of the contours. If the number of vertex points in the approximate contour is 4 then we compute the aspect ratio to make a difference betwee
 Swift: Detecting rectangles. Detect and extract a rectangular… | by ... | Detect and extract a rectangular regions of an image, in Swift!
 Drawing selectable rectangles on an image - JupyterLab - Jupyter ... | Hi  I’m new to using Jupiter Lab and to Python - trying to find a way to perform the following :  I want to display an image (a page from a document) - and draw rectangles on top of it (bounding boxes of different texts). I get the list of bounding boxes from an external server using rest api.  I managed to do that using PIL and request easily.  But now - I want to be able to “select” specific rectangles by clicking on the image - and get the boxes of those rectangles (so the user can select the...