Beispiel #1
0
def contrastStretching(img, mask, lwr_prctile, upr_prctile):
    print("Contrast stretching...")
    mm = img[mask > 0]
    p_lwr = np.percentile(mm,lwr_prctile)
    p_upr = np.percentile(mm,upr_prctile)
    opImg = rescale(img,in_range=(p_lwr,p_upr))  
    return opImg
Beispiel #2
0
def videoWrite(arr, fileName, fps=30, axis=0):
    if axis ==-1:
        arr = arr.transpose([2, 0, 1])
#     arr_ = (arr - arr.min())/(arr.max()-arr.min())*255
#     arr_ = arr_.astype('uint8')
    arr = rescale(arr, out_range='uint8').astype('uint8')
    with imageio.get_writer(fileName, fps=fps) as writer:
        for im in arr:
            writer.append_data(im)
Beispiel #3
0
def montage_projection(im_dir, trange=None, context=None):
    """
    Generate a montage of x projections.

    im_dir : str, path to directory containing [x,y,z] data saved as tif
    
    trange : object which can be used for linear indexing, set of timepoints to use

    context : spark context object for parallelization
    """
    import thunder as td
    import skimage.external.tifffile as tif
    from glob import glob
    from skimage.util.montage import montage2d
    from skimage.exposure import rescale_intensity as rescale
    import numpy as np
    from skimage import io

    exp_name = im_dir.split('/')[-2]

    print('Exp name: {0}'.format(exp_name))
    ims = td.images.fromtif(im_dir + 'TM*.tif', engine=context)
    print('Experiment dims: {0}'.format(ims.shape))
    
    if trange is None:
        trange = np.arange(ims.shape[0])
    
    ims_cropped = ims[trange].median_filter([1,3,3])
    dims = ims_cropped.dims
    
    from scipy.ndimage import percentile_filter
    float_dtype = 'float32'
    
    def my_dff(y, perc, window): 
        baseFunc = lambda x: percentile_filter(x.astype(float_dtype), perc, window, mode='reflect')
        b = baseFunc(y)
        return ((y - b) / (b + .1))

    dff_fun = lambda v: my_dff(v, 15, 800) 
    chop = 16

    reshape_fun = lambda v: v.reshape(dims[0], dims[1], chop, dims[2] // chop)
    montage_fun = lambda v: montage2d(v.T).T

    def im_fun(v):
        return montage_fun(reshape_fun(v).max(3))
    
    out_dtype = 'uint16'
    
    montage_ims = ims_cropped.map_as_series(dff_fun, value_size=ims_cropped.shape[0], dtype=float_dtype, chunk_size='35').map(im_fun)
    dff_lim = montage_ims.map(lambda v: [v.max(), v.min()]).toarray()
    rescale_fun = lambda v: rescale(v, in_range=(dff_lim.min(), dff_lim.max()), out_range=out_dtype).astype(out_dtype)

    montage_rescaled = montage_ims.map(rescale_fun).toarray()[:,-1::-1,:]
    return montage_rescaled
Beispiel #4
0
def apply_dff(images, dff_fun, out_dtype):
    from numpy import array
    from skimage.exposure import rescale_intensity as rescale

    images_dff = images.map_as_series(
        dff_fun, value_size=images.shape[0], dtype=images.dtype
    )

    bounds = images_dff.map(lambda v: array([v.min(), v.max()])).toarray()
    mn, mx = bounds.min(), bounds.max()
    images_rescaled = images_dff.map(
        lambda v: rescale(v, in_range=(mn, mx), out_range=out_dtype).astype(out_dtype)
    )
    dff_lim = (mn, mx)
    return images_rescaled, dff_lim
Beispiel #5
0
import main
import matplotlib.pyplot as plt
from skimage.measure import compare_ssim as ssim
from skimage.exposure import rescale_intensity as rescale
import numpy as np

s = main.Server()
s.handler()
i = main.Image()
im = i.return_image(size=32)
hadamard_samples = s.get_data()
o = main.Single()
res1 = o.reconstruction(hadamard_samples,
                        32,
                        method='hadamard',
                        mask='hadamard')
s1 = ssim(
    rescale(res1, out_range=(0, 255)).astype("uint8"), im.astype("uint8"))
print(s1)
plt.imshow(res1)
Beispiel #6
0
"""


def imshow(im):
    plt.figure()
    plt.gray()
    plt.imshow(im)
    plt.show()


i = main.Image()
per = np.arange(0.1, 1.1, 0.1)
for j in per:
    i = main.Image()
    im = i.return_image(size=64)
    o = main.Single()

    tic = time.clock()
    s = main.Simulator(im, mode="random")
    samples = []
    for i in range(0, int((64 * 64) * j)):
        samples.append(s.get_sample())
        """
        c.buffer(bytes(str(s.get_sample()),'utf-8'))
        """
    res1 = o.reconstruction(samples, im.shape[0], method='direct_inverse')
    toc = time.clock()
    t1 = toc - tic
    s1 = ssim(rescale(res1, out_range=(0, 255)), im)
    print(str(j) + " " + str(s1) + " " + str(t1))
Beispiel #7
0
def depth_project(data, axis=0, cmap="jet", clim="auto", mode="sum"):
    """
    Generate an RGB "depth projection" of a 3D numpy array.

    Input data are normalized to [0,1] and data values along the projection axis are mapped
    to indices in a linear RGBA colormap.

    If `mode` is `sum`, for each element along the projection axis there is a color, and the brightness of this color is
    scaled by the intensity values of the data. The output is the sum of the values along the projection axis,
    i.e. a 3D array with the last dimension containing RGB values.

    If 'mode' is 'max', then the intensity values are determined by the maximum intensity projection of data over the
    projection axis, and the color of each pixel in the maximum projection is specified by the index where the maximum
    value was attained. In the case of repeated maxmimal values, the index of the first is used.

    data : 3D numpy array

    axis : int denoting an axis to project over

    cmap : string denoting a matplotlib colormap

    clim : string, or list or tuple with length 2.
        This argument determines the minimum and maximum intensity values to use before rescaling the data to the range
        [0,1]. The default value, 'auto', specifies that the minimum and maximum values of the input data will be mapped
        to [0,1].

    mode : string determining which projection mode to use


    """
    from numpy import linspace, zeros, array, argmax, all
    from skimage.exposure import rescale_intensity as rescale
    from matplotlib.cm import get_cmap

    if clim == "auto":
        clim = data.min(), data.max()

    cm = get_cmap(cmap)(linspace(0, 1, data.shape[axis]))
    data_r = rescale(data.astype("float32"), in_range=clim, out_range=(0, 1))

    if mode == "sum":

        cvol = zeros((*data.shape, 4))

        data_r = array([data_r] * cm.shape[-1]).transpose(1, 2, 3, 0)
        for ind in range(cvol.shape[axis]):
            slices = [slice(None)] * cvol.ndim
            slices[axis] = ind
            slices = tuple(slices)
            cvol[slices] = cm[ind] * data_r[slices]

        proj = cvol.sum(axis)
        proj[:, :, -1] = 1
        proj[:, :, :-1] = rescale(
            proj[:, :, :-1], in_range=(0, proj.max()), out_range=(0, 1)
        )

    elif mode == "max":
        mx = data_r.max(axis)
        dp = argmax(data_r, axis)
        proj = (cm[dp, :].T * mx.T).T

    else:
        raise ValueError('Mode must be "sum" or "max"')

    return proj