preprocess_yoco / preprocess.py
nathbns's picture
Upload 11 files
9b4f4f7 verified
# Preprocessing function adapted for Gradio
# This script preprocesses original pictures and turns them into 2D-projections.
import numpy as np
import cv2
from matplotlib import pyplot as plt
from rescale import *
from slid import detect_lines
from laps import LAPS
from llr import LLR, llr_pad
def preprocess_image_from_array(img_array):
'''
Preprocesses an image from a numpy array (RGB format).
Args:
img_array: numpy array of the image in RGB format
Returns:
Preprocessed image as numpy array
'''
# Convert RGB to BGR for OpenCV (if needed)
# Gradio images are usually in RGB format, but cv2.imread expects BGR
# Since we're getting an array, we need to convert RGB to BGR
if len(img_array.shape) == 3 and img_array.shape[2] == 3:
res = img_array[..., ::-1] # RGB to BGR
else:
res = img_array.copy()
# Crop twice, just like Czyzewski et al. did
for _ in range(2):
img, shape, scale = image_resize(res)
lines = detect_lines(img)
lattice_points = LAPS(img, lines)
# Sometimes LLR() or llr_pad() will produce an error. In this case,
# the picture needs to be retaken
inner_points = LLR(img, lattice_points, lines)
four_points = llr_pad(inner_points, img) # padcrop
try:
res = crop(res, four_points, scale)
except:
print("WARNING: couldn't crop around outer points")
res = crop(res, inner_points, scale)
# Convert BGR back to RGB for display
return res[..., ::-1]