ID_INFO / preprocess.py
Rakib023's picture
Create preprocess.py
17656b2 verified
raw
history blame contribute delete
985 Bytes
import cv2
import numpy as np
import os
import logging
def read_image(image_path, is_uploaded=False):
if is_uploaded:
img_bytes = image_path.read()
img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
return img
return cv2.imread(image_path)
def extract_id_card(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.adaptiveThreshold(
blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 11, 2
)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(largest)
roi = img[y:y+h, x:x+w]
path = "data/intermediate/id_roi.jpg"
cv2.imwrite(path, roi)
return roi, path
def save_image(image, filename, path):
full_path = os.path.join(path, filename)
cv2.imwrite(full_path, image)
return full_path