JacobLinCool/captcha-recognizer
1
1import cv22import numpy as np3 4 5def preprocess(image: np.ndarray) -> np.ndarray:6 # Upscale, interpolation with nearest neighbor7 image = cv2.resize(image, (0, 0), fx=3, fy=3, interpolation=cv2.INTER_NEAREST)8 9 # Denoise gray-like pixels10 hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)11 mask = cv2.inRange(hsv, (0, 70, 70), (255, 255, 255))12 mask = cv2.bitwise_not(mask)13 image[np.where(mask)] = 25514 15 # Convert to binary16 image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)17 _, image = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU)18 19 # Fix some holes20 kernel = np.ones((3, 3), np.uint8)21 image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=2)22 23 # add padding24 image = cv2.copyMakeBorder(25 image, 5, 5, 5, 5, cv2.BORDER_CONSTANT, value=(255, 255, 255)26 )27 28 return image29 