find a white square bigger than 500 pixels, with known rotation and highlight it in python in python

To find a white square bigger than 500 pixels with a known rotation, you can use Computer Vision techniques based on Contours Detection, to identify a rectangular shape in the image, applying some filters to reduce the noise and improve the extraction of the edges. Here is one way to approach this problem using Python and OpenCV:

main.py
import cv2

# Load image
image = cv2.imread("image.jpg")

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply threshold to binarize image
thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)[1]

# Apply morphology to fill holes and reduce noise
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# Find contours in the image
cnts, _ = cv2.findContours(morph.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Loop over the contours and filter rectangle shapes
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    if len(approx) == 4:
        (x, y, w, h) = cv2.boundingRect(approx)
        if w > 500 and h > 500:
            # Draw a green rectangle and label it as square
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(image, "Square", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
1069 chars
33 lines

In this code, we first read an image in BGR format and convert it to grayscale. Then, we apply a threshold to binarize the image, followed by a morphological operation to fill holes and reduce noise. After that, we use the findContours function to detect the contours in the image. Using the approxPolyDP method, we apply a filter to detect rectangle shapes with four vertices. We then check that the width and height of these rectangles are greater than 500 pixels, and highlight them in green with a label using the rectangle and putText functions. Finally, we display the annotated image using imshow.

Note that the rotation of the rectangle is not taken into account in this code, as the question did not provide enough information on how to determine the rotation angle. If you have a known rotation angle, you can rotate the image using cv2.warpAffine before applying the contour detection.

related categories

gistlibby LogSnag