CoolFace
Apppublic

ericup/celldetection

sourceHugging Faceapache-2.0updated 11mo agoView on Hugging Face
3likes
prep.py64 linesDownload Raw Back to root
1import celldetection as cd2import numpy as np3from skimage import img_as_ubyte, exposure4from PIL import ImageFile5 6ImageFile.LOAD_TRUNCATED_IMAGES = True7 8__all__ = ['normalize_img', 'normalize_channel', 'multi_norm']9 10 11def normalize_img(img, gamma_spread=17, lower_gamma_bound=.6, percentile=99.88):12    log = []13    if img.dtype.kind == 'f':  # floats14        if img.max() < 256:15            img = img_as_ubyte(img / 255)16            log.append('img_as_ubyte')17        else:18            v = 99.9519            img = cd.data.normalize_percentile(img, v)20            log.append(f'cd.data.normalize_percentile(img, {v})')21    elif img.itemsize > 1:22        img = cd.data.normalize_percentile(img, percentile)23        log.append(f'cd.data.normalize_percentile(img, {percentile})')24    mean_thresh = np.pi * gamma_spread25    if img.mean() < mean_thresh:26        gamma = (1 - ((np.cos(1 / gamma_spread * img.mean()) + 1) / 2)) * (1 - lower_gamma_bound) + lower_gamma_bound27        log.append(f'(img / 255) ** {gamma}')28        img = (img / 255) ** gamma29        img = img_as_ubyte(img)30    return img, log31 32 33def normalize_channel(img, lower=1, upper=99):34    non_zero_vals = img[np.nonzero(img)]35    percentiles = np.percentile(non_zero_vals, [lower, upper])36    if percentiles[1] - percentiles[0] > 0.001:37        img_norm = exposure.rescale_intensity(img, in_range=(percentiles[0], percentiles[1]), out_range='uint8')38    else:39        img_norm = img40    return img_norm.astype(np.uint8)41 42 43def multi_norm(img, method):44    if method == 'prov':45        img = normalize_channel(img)46    elif method == 'rand-mix' or method == 'cstm-mix':47        img0 = normalize_channel(img)48        img1, log = normalize_img(img)49        if method == 'rand-mix':50            alpha = np.random.uniform(0., 1.)51        else:52            is_grayscale = img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1)53            alpha = 0.54            if not is_grayscale:55                if img[..., 2].mean() > 200 and img[..., 2].std() < 20:56                    alpha = 1.57            else:58                if img1.mean() < 45 and img1.std() < 33:59                    alpha = .560        img = np.clip(alpha * img0 + (1 - alpha) * img1, 0, 255).astype(img0.dtype)61    else:62        img, log = normalize_img(img)63    return img64