OpenCV-based Square Detection in Images

  • Share this:

Code introduction


This function uses functions from the OpenCV library to detect rectangular regions in an image, assuming these regions are squares. It first converts the image to a grayscale image, then creates a binary image using thresholding. It then finds contours in the binary image and filters out possible square contours. Finally, it calculates the bounding rectangles for each square and draws these rectangles on the original image.


Technology Stack : OpenCV, NumPy

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def find_squares(image):
    import cv2
    import numpy as np
    
    # Convert the image to gray scale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Use thresholding to create a binary image
    _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
    
    # Find contours in the binary image
    contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # Filter out small contours that are not squares
    squares = [contour for contour in contours if cv2.contourArea(contour) > 1000]
    
    # Find the bounding rectangle for each square
    rectangles = [cv2.boundingRect(contour) for contour in squares]
    
    # Draw the rectangles on the original image
    for rect in rectangles:
        x, y, w, h = rect
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
    
    return image                
              
Tags: