# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/focus_stacking.ipynb (unless otherwise specified).

__all__ = ['focus_stack']

# Cell
# export
import pandas
import dotenv
import os
import matplotlib.pyplot as plt
from importlib import reload
import numpy
import warnings

warnings.filterwarnings('error')

dotenv.load_dotenv()

# Cell
import cv2
from c7m import load_tiff_images
from skimage import img_as_float
from tqdm.notebook import tqdm
from PIL import Image

# Internal Cell

def doLap(image):
    kernel_size = 5         # Size of the laplacian window
    blur_size = 5           # How big of a kernal to use for the gaussian blur
                            # Generally, keeping these two values the same or very close works well
                            # Also, odd numbers, please...

    blurred = cv2.GaussianBlur(image, (blur_size,blur_size), 0)
    return cv2.Laplacian(blurred, cv2.CV_64F, ksize=kernel_size)

# Cell
def focus_stack(images):
    laps = []
    for i in range(len(images)):
        laps.append(doLap(images[i]))

    laps = numpy.asarray(laps)

    output = numpy.zeros(shape=images[0].shape, dtype=images[0].dtype)

    abs_laps = numpy.absolute(laps)
    maxima = abs_laps.max(axis=0)
    bool_mask = abs_laps == maxima
    mask = bool_mask.astype(numpy.uint8)
    for i in range(0,len(images)):
        output = cv2.bitwise_not(images[i],output, mask=mask[i])
    return cv2.bitwise_not(output)