find white square 100 by 100 pixels in binary image in python

You can use the OpenCV library to find the position of a white square of size 100 x 100 pixels in a binary image. Here is the code snippet that does that:

main.py
import cv2
import numpy as np

# Load the binary image
img = cv2.imread('binary_image.png', cv2.IMREAD_GRAYSCALE)

# Convert to binary image
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# Define the kernel
kernel = np.ones((100, 100), np.uint8)

# Perform erosion and dilation to remove noise and find blobs
binary = cv2.erode(binary, kernel, iterations=1)
binary = cv2.dilate(binary, kernel, iterations=1)

# Find contours
contours, _ = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

# Look for the square contours
for c in contours:
    # Get the perimeter of the contour
    peri = cv2.arcLength(c, True)

    # Approximate the polygon with less vertices
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)

    # If the contour is a square of size 100x100 pixels, draw a rectangle around it
    if len(approx) == 4 and cv2.contourArea(c) == 10000:
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)

# Save the output image
cv2.imwrite('output_image.png', img)
1057 chars
35 lines

This code loads the binary image, create a kernel of size 100 x 100 pixels, and perform erosion and dilation operations to remove noise and find blobs. Then, it finds the contours in the binary image, and checks if any of them has the shape of a square of size 100 x 100 pixels. If it does, then it draws a blue rectangle around it. Finally, it saves the output image.

related categories

gistlibby LogSnag