I have this dilated mask and I’m trying to find a contour of the largest central square block.
here is the code I have, the issue is that it doesn’t return a region that fits the criteria and the contours that it does find are the smaller squares in the grid:
contours, _ = cv2.findContours(dilated_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
area = cv2.contourArea(contour)
print(f"Contour {i + 1}: Area = {area}")
# Loop through contours to find the central frame
for contour in contours:
# Approximate the contour to a polygon
epsilon = 0.05 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# Check if the polygon has 4 vertices (rectangle)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(approx)
# Aspect ratio check
aspect_ratio = w / float(h)
if 0.8 < aspect_ratio < 1.2: # Roughly square
# **Size Constraints**
if 100 < w < 1000 and 100 < h < 1000: # Adjust these bounds
print(f"Detected frame with width={w}, height={h}")
# Extract the region of interest
region = barnacles[y:y+h, x:x+w]
# Display the region
region_rgb = cv2.cvtColor(region, cv2.COLOR_BGR2RGB)
plt.imshow(region_rgb)
plt.title("Cropped Frame")
plt.axis("off")
plt.show()
return region