import cv2 import numpy as np def detect_large_coherent_structures(image: np.array): """Detects large coherent structures on an image. References: https://stackoverflow.com/questions/60259169/how-to-group-nearby-contours-in-opencv-python-zebra-crossing-detection """ if len(image.shape) > 2: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.threshold(image, 253, 255, cv2.THRESH_BINARY)[1] dilate_kernel = cv2.getStructuringElement(cv2.MORPH_OPEN, (5, 5)) dilate = cv2.dilate(~image, dilate_kernel, iterations=4) close_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20)) close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, close_kernel, iterations=1) counts, _ = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return counts