import cv2 import numpy as np from config.settings import THRESHOLD def preprocess_image(img): if hasattr(img, "convert"): img = np.array(img) if len(img.shape) == 3: gray = cv2.cvtColor( img, cv2.COLOR_RGB2GRAY ) else: gray = img.copy() # Increase contrast gray = cv2.equalizeHist(gray) # Detect pencil lines (threshold now driven by config, not hardcoded) _, binary = cv2.threshold( gray, THRESHOLD, 255, cv2.THRESH_BINARY_INV ) # Close tiny gaps kernel = np.ones((3, 3), np.uint8) binary = cv2.morphologyEx( binary, cv2.MORPH_CLOSE, kernel, iterations=2 ) return binary def remove_noise(binary): kernel = np.ones((2, 2), np.uint8) return cv2.morphologyEx( binary, cv2.MORPH_OPEN, kernel )