import cv2 import numpy as np def preprocess_image(img): if len(img.shape) == 3: gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) else: gray = img.copy() gray = cv2.GaussianBlur(gray, (3, 3), 0) _, binary = cv2.threshold( gray, 180, 255, cv2.THRESH_BINARY_INV ) kernel = np.ones((2, 2), np.uint8) binary = cv2.morphologyEx( binary, cv2.MORPH_CLOSE, kernel ) return binary def remove_noise(binary): kernel = np.ones((2, 2), np.uint8) cleaned = cv2.morphologyEx( binary, cv2.MORPH_OPEN, kernel ) return cleaned