""" Image preprocessing module using OpenCV. Provides optional enhancements for scanned/photographed handwritten documents. """ import os import cv2 import numpy as np from PIL import Image import io import base64 class ImagePreprocessor: """Preprocesses images to improve handwritten text extraction quality.""" @staticmethod def load_image_from_bytes(image_bytes: bytes) -> np.ndarray: """Load an image from raw bytes into an OpenCV array.""" nparr = np.frombuffer(image_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if img is None: raise ValueError("Could not decode image from provided bytes.") return img @staticmethod def to_bytes(img: np.ndarray, ext: str = ".jpg") -> bytes: """Convert an OpenCV image array back to bytes.""" success, buffer = cv2.imencode(ext, img) if not success: raise ValueError(f"Failed to encode image to {ext}") return buffer.tobytes() @staticmethod def to_base64(img: np.ndarray, ext: str = ".jpg") -> str: """Convert an OpenCV image to a base64-encoded string.""" img_bytes = ImagePreprocessor.to_bytes(img, ext) return base64.b64encode(img_bytes).decode("utf-8") @staticmethod def auto_rotate(img: np.ndarray) -> np.ndarray: """ Detect and correct image rotation/skew using text line detection. Uses Hough line transform to find dominant text orientation. """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Edge detection edges = cv2.Canny(gray, 50, 150, apertureSize=3) # Detect lines lines = cv2.HoughLinesP( edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10 ) if lines is None or len(lines) == 0: return img # No lines detected, return as-is # Calculate angles of detected lines angles = [] for line in lines: pts = line.reshape(-1) if len(pts) < 4: continue x1, y1, x2, y2 = pts[:4] if x2 - x1 == 0: continue angle = np.degrees(np.arctan2(y2 - y1, x2 - x1)) # Only consider near-horizontal lines (text lines) if abs(angle) < 45: angles.append(angle) if not angles: return img # Use median angle to avoid outlier influence median_angle = np.median(angles) # Only rotate if skew is significant (> 0.5 degrees) if abs(median_angle) < 0.5: return img # Rotate to correct skew (h, w) = img.shape[:2] center = (w // 2, h // 2) rotation_matrix = cv2.getRotationMatrix2D(center, median_angle, 1.0) # Calculate new bounding box size cos = np.abs(rotation_matrix[0, 0]) sin = np.abs(rotation_matrix[0, 1]) new_w = int(h * sin + w * cos) new_h = int(h * cos + w * sin) rotation_matrix[0, 2] += (new_w / 2) - center[0] rotation_matrix[1, 2] += (new_h / 2) - center[1] rotated = cv2.warpAffine( img, rotation_matrix, (new_w, new_h), borderMode=cv2.BORDER_REPLICATE ) return rotated @staticmethod def enhance_contrast(img: np.ndarray) -> np.ndarray: """ Improve contrast using CLAHE (Contrast Limited Adaptive Histogram Equalization). Applied gently to preserve handwriting strokes. """ # Convert to LAB color space for luminance-only enhancement lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) l_channel, a, b = cv2.split(lab) # Apply CLAHE with conservative parameters to avoid destroying strokes clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) cl = clahe.apply(l_channel) # Merge back enhanced = cv2.merge((cl, a, b)) result = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR) return result @staticmethod def reduce_noise(img: np.ndarray) -> np.ndarray: """ Reduce noise while preserving handwriting edges. Uses non-local means denoising — gentler than Gaussian blur. """ # fastNlMeansDenoisingColored with conservative strength denoised = cv2.fastNlMeansDenoisingColored( img, None, 6, 6, 7, 21 ) return denoised @staticmethod def resize_if_needed(img: np.ndarray, max_dimension: int = 4096) -> np.ndarray: """ Resize image if any dimension exceeds max_dimension. Maintains aspect ratio. """ h, w = img.shape[:2] if max(h, w) <= max_dimension: return img scale = max_dimension / max(h, w) new_w = int(w * scale) new_h = int(h * scale) resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA) return resized @staticmethod def sharpen(img: np.ndarray) -> np.ndarray: """ Gently sharpen the image to make handwriting strokes clearer. Uses an unsharp mask approach. """ gaussian = cv2.GaussianBlur(img, (0, 0), 3) sharpened = cv2.addWeighted(img, 1.3, gaussian, -0.3, 0) return sharpened @classmethod def preprocess( cls, image_bytes: bytes, auto_rotate: bool = True, enhance_contrast: bool = True, reduce_noise: bool = True, sharpen: bool = True, resize: bool = True, max_dimension: int = 4096 ) -> tuple[bytes, dict]: """ Apply the full preprocessing pipeline. Args: image_bytes: Raw image file bytes. auto_rotate: Whether to correct skew/rotation. enhance_contrast: Whether to apply CLAHE contrast enhancement. reduce_noise: Whether to apply noise reduction. sharpen: Whether to sharpen handwriting strokes. resize: Whether to resize oversized images. max_dimension: Maximum pixel dimension for resize. Returns: Tuple of (processed_image_bytes, processing_info_dict). """ steps_applied = [] try: img = cls.load_image_from_bytes(image_bytes) original_shape = img.shape[:2] except Exception as e: return image_bytes, { "error": f"Could not load image: {str(e)}", "steps_applied": [], "original_size": None, "processed_size": None } # Step 1: Resize if needed (do first to speed up subsequent operations) if resize: img = cls.resize_if_needed(img, max_dimension) if img.shape[:2] != original_shape: steps_applied.append("resize") # Step 2: Auto-rotate / deskew if auto_rotate: before_shape = img.shape img = cls.auto_rotate(img) steps_applied.append("auto_rotate") # Step 3: Noise reduction if reduce_noise: img = cls.reduce_noise(img) steps_applied.append("noise_reduction") # Step 4: Contrast enhancement if enhance_contrast: img = cls.enhance_contrast(img) steps_applied.append("contrast_enhancement") # Step 5: Sharpening if sharpen: img = cls.sharpen(img) steps_applied.append("sharpen") processed_bytes = cls.to_bytes(img, ".jpg") processed_shape = img.shape[:2] info = { "steps_applied": steps_applied, "original_size": {"height": original_shape[0], "width": original_shape[1]}, "processed_size": {"height": processed_shape[0], "width": processed_shape[1]}, "original_bytes": len(image_bytes), "processed_bytes": len(processed_bytes) } return processed_bytes, info