Ejemplo n.º 1
0
def register_directory_pairwise(image_dir,
                                out_dir='',
                                save_txt=True,
                                save_image=False,
                                **kwargs):
    '''Run FFT-based rigid image registration comparing sequential images
        in a directory
    
    image_dir : str
        The path to the image files
        
    out_dir : str
        The path to write the output image fles

    save_txt : bool
        Write the affine transformation parameters to a .txt file
    save_image : bool
        save the registered output file
        
    **kwargs : dict
        The arguments for the imreg_dft function
    
    '''

    imd = glob.glob(image_dir + '/*.tif')

    imd1 = list(imd)
    imd2 = list(imd)
    imd1.pop(-1)
    imd2.pop(0)

    test_frame = imread2(imd1[0])
    if (len(test_frame.shape) > 2) and (test_frame.shape[-1] > 1):
        rgb_flag = True
        warnings.warn("RGB image detected, first channel will be used.")
    else:
        rgb_flag = False

    text_file = open(image_dir + "_transform_params.txt", "w")

    for im1, im2 in zip(imd1, imd2):
        frame_a, frame_b = imread2(im1), imread2(im2)
        if rgb_flag:
            frame_a, frame_b = frame_a[:, :, 0], frame_b[:, :, 0]

        result = ird.similarity(frame_a, frame_b, **kwargs)
        transform_params = result['scale'], result['angle'], result['tvec']

        if save_image:
            imname = os.path.split(im1)[-1][:-4]
            param_str = '_scale'+str(scale)+'_angle'+str(rotangle)\
                        +'_trans'+str(transvec[0])+'_'+str(transvec[1])
            savestr = out_dir + '/' + imname + '.png'
            toimage(regim).save(savestr)
            pass

        if save_txt:
            print("{0}\t{1}\t{2}".format(*transform_params), file=text_file)

    text_file.close()
Ejemplo n.º 2
0
def overlay_images(dir1, dir2, out_dir, ftype1='.tif', ftype2='.tif'):
    '''
    Given two directories full of images, load one image from each directory and 
    overlay it on the other with the specified tint and color

    Parameters
    ----------

    dir1 : str
        Path to the directory of images that will be used as the background

    dir2 : str
        Path to the directory of images that will be tinted and overlaid

    out_dir : str
        Path to the directory at which output will be saved

    '''
    tint_color = (127 / 255., 255 / 255., 212 / 255.)

    # rvals, gvals, bvals = stack2*fullcmap[:, 0], stack2*fullcmap[:, 1], stack2*fullcmap[:, 2]
    #                 stack2 = concatenate([rvals[...,newaxis],gvals[...,newaxis],bvals[...,newaxis]],axis=-1)

    bg_ims = glob.glob(dir1 + '/*' + ftype1)
    fg_ims = glob.glob(dir2 + '/*' + ftype2)

    if len(bg_ims) != len(bg_ims):
        warnings.warn(
            "The two image directories contain different numbers of images.")

    for ind, bg_im in enumerate(bg_ims):

        fg_im = fg_ims[ind]
        im1 = imread2(bg_im)
        im2 = imread2(fg_im)

        # threshold image from one side
        # ones just pass through, anything less than one filters
        im2[im2 < .5] = 1.0

        finim = im1 * im2

        bg_name = os.path.split(bg_im)[-1][:-4]
        fg_name = os.path.split(fg_im)[-1][:-4]
        savestr = out_dir + '/' + bg_name + '_times_' + fg_name + '.png'
        toimage(finim, cmin=0.0, cmax=max(ravel(finim))).save(savestr)
Ejemplo n.º 3
0
def overlay_images(dir1, dir2, out_dir, ftype1='.tif',ftype2='.tif'):
    '''
    Given two directories full of images, load one image from each directory and 
    overlay it on the other with the specified tint and color

    Parameters
    ----------

    dir1 : str
        Path to the directory of images that will be used as the background

    dir2 : str
        Path to the directory of images that will be tinted and overlaid

    out_dir : str
        Path to the directory at which output will be saved

    '''
    tint_color = (127/255., 255/255., 212/255.)

# rvals, gvals, bvals = stack2*fullcmap[:, 0], stack2*fullcmap[:, 1], stack2*fullcmap[:, 2]
#                 stack2 = concatenate([rvals[...,newaxis],gvals[...,newaxis],bvals[...,newaxis]],axis=-1)

    bg_ims = glob.glob(dir1+'/*'+ftype1)
    fg_ims = glob.glob(dir2+'/*'+ftype2)

    if len(bg_ims) != len(bg_ims):
        warnings.warn("The two image directories contain different numbers of images.")

    for ind, bg_im in enumerate(bg_ims):

        fg_im = fg_ims[ind]
        im1 = imread2(bg_im)
        im2 = imread2(fg_im)

        # threshold image from one side
        # ones just pass through, anything less than one filters
        im2[im2 < .5] = 1.0

        finim = im1*im2

        bg_name = os.path.split(bg_im)[-1][:-4]
        fg_name = os.path.split(fg_im)[-1][:-4]
        savestr = out_dir +'/'+bg_name+'_times_'+fg_name+'.png'
        toimage(finim, cmin=0.0, cmax=max(ravel(finim))).save(savestr)
Ejemplo n.º 4
0
def piv_directory(image_dir, out_dir, **kwargs):
    '''Run PIV on a time series
    
    image_dir : str
        The path to the image files
        
    out_dir : str
        The path to write the output .txt fles
        
    **kwargs : dict
        The arguments for the PIV function
    
    '''

    imd = glob.glob(image_dir + '\*.tif')

    imd1 = list(imd)
    imd2 = list(imd)
    imd1.pop(-1)
    imd2.pop(0)
    for im1, im2 in zip(imd1, imd2):
        frame_a = imread2(im1)
        frame_b = imread2(im2)
        # xyuv = piv_pair(frame_a, frame_b, winsize=60, overlap=30,search_size=100)
        xyuv = piv_pair(frame_a, frame_b, **kwargs)
        x, y, u, v, mask = xyuv

        imname = os.path.split(im1)[-1][:-4]

        param_str = ''

        if 'winsize' in kwargs:
            param_str += '_window' + str(kwargs['winsize'])
        if 'overlap' in kwargs:
            param_str += '_overlap' + str(kwargs['overlap'])
        if 'sch_size' in kwargs:
            param_str += '_sch' + str(kwargs['sch_size'])

        openpiv.tools.save(x, y, u, v, mask,
                           out_dir + '/' + imname + param_str + '.txt')
Ejemplo n.º 5
0
def register_directory(image_dir,
                       ref_im='',
                       out_dir='',
                       save_txt=True,
                       save_image=False,
                       **kwargs):
    '''Run FFT-based rigid image registration comparing images in
        a directory to a reference image
    
    Inputs
    ------
    image_dir : str
        The path to the image files
        
    ref_im : array
        The image to which each image in hte directory will be
        registered. Defaults to the first image in the directory

    out_dir : str
        The path to write the output .txt fles

    save_txt : bool
        Write the affine transformation parameters to a .txt file

    save_image : bool
        save the registered output file
        
    **kwargs : dict
        The arguments for the imreg_dft function
    
    '''

    imd = glob.glob(image_dir + '/*.tif')

    imd1 = list(imd)
    imd1.pop(-1)

    test_frame = imread2(imd1[0])
    if (len(test_frame.shape) > 2) and (test_frame.shape[-1] > 1):
        rgb_flag = True
        test_frame = test_frame[:, :, 0]
        warnings.warn("RGB image detected, first channel will be used.")
    else:
        rgb_flag = False

    if not ref_im:
        ref_im = test_frame

    # text_file = open(out_dir+'/'+"transform_params.txt", "w")
    text_file = open(image_dir + "_transform_params.txt", "w")

    for im1 in imd1:
        frame_a = imread2(im1)
        if rgb_flag:
            frame_a = frame_a[:, :, 0]

        result = ird.similarity(ref_im, frame_a, **kwargs)
        transform_params = result['scale'], result['angle'], result['tvec']

        if save_image:
            imname = os.path.split(im1)[-1][:-4]
            param_str = '_scale'+str(scale)+'_angle'+str(rotangle)\
                        +'_trans'+str(transvec[0])+'_'+str(transvec[1])
            savestr = out_dir + '/' + imname + '.png'
            toimage(result['timg']).save(savestr)
            pass

        if save_txt:
            print("{0}\t{1}\t{2}".format(*transform_params), file=text_file)

    text_file.close()
Ejemplo n.º 6
0
def overlay_images(dir1, dir2, out_dir, ftype1='.png',ftype2='.png'):
    '''
    Given two directories full of images, load one image from each directory and 
    overlay it on the other with the specified tint and color

    Parameters
    ----------

    dir1 : str
        Path to the directory of images that will be used as the background

    dir2 : str
        Path to the directory of images that will be tinted and overlaid

    out_dir : str
        Path to the directory at which output will be saved

    '''
  

    bg_ims = glob.glob(dir1+'/*'+ftype1)
    fg_ims = glob.glob(dir2+'/*'+ftype2)
    bg_color = (153/255., 204/255., 255/255.)
    fg_color = (255/255., 204/255., 102/255.)

    if len(bg_ims) != len(bg_ims):
        warnings.warn("The two image directories contain different numbers of images.")
    
    for ind, bg_im in enumerate(bg_ims):
        
        fg_im = fg_ims[ind]
        im1 = imread2(bg_im)
        if len(im1.shape)==3:
            im1 = sum(im1, axis=2)/3.

        im2 = imread2(fg_im)
        if len(im2.shape)==3:
            im2 = sum(im2, axis=2)/3.


        im2_norm = im2.astype(double)/255.
        im2_mask = im2_norm < .2
        
        im2_norm[im2_mask] = 0.0
        just_bigger_sizes = im2_norm*im1
        just_bigger_sizes = grey_dilation(just_bigger_sizes, size=(2,2))
        
        im2_norm = im2.astype(double)/255.
#         im2_mask = im2_norm > .2
        im2_norm[~im2_mask] = 0.0
        just_smaller_sizes = im2_norm*im1
        
        just_smaller_sizes = grey_dilation(just_smaller_sizes, size=(2,2))
        
        if ind==0:
            norm_factor1 = max(ravel(just_smaller_sizes)) 
            norm_factor2 = max(ravel(just_bigger_sizes)) 
        just_smaller_sizes = (just_smaller_sizes.astype(double)/norm_factor1)*255
        just_bigger_sizes = (just_bigger_sizes.astype(double)/norm_factor2)*255
        
        
        rgb_bg = concatenate([(just_smaller_sizes*chan)[...,newaxis] for chan in bg_color],axis=-1)
        
        rgb_img = concatenate([(just_bigger_sizes*chan)[...,newaxis] for chan in fg_color],axis=-1)
        
        finim = rgb_bg + rgb_img

        bg_name = os.path.split(bg_im)[-1][:-4]
        fg_name = os.path.split(fg_im)[-1][:-4]
        savestr = out_dir +'/'+bg_name+'_times_'+fg_name+'.png'

        if ind==0:
            cmax0=max(ravel(finim))
        toimage(finim, cmin=0.0, cmax=cmax0).save(savestr)
Ejemplo n.º 7
0
def sliding_zproj_internal(frames_list, frames_to_merge, out_dir, **kwargs):
    '''
    This code is optimized for computers that DO NOT have enough 
    RAM to store all the images in memory, but which DO have enough 
    RAM to store an entire z-projection stack in memory
    
    Parameters
    ----------
    frames_list : list of str
        list of image files
        
    frames_to_merge : int
        The number of frames to merge to form a single streamline image
    
    out_dir : str
        path to directory where streamline files are saved
        
    take_diff : bool
        whether to take the difference of consecutive frames
    
    diff_order : int
        the order of the difference in frames when take_diff is used

    subtract_median : bool
        For each substack, subtract the median before taking the 
        z projection

    subtract_first : bool
        For each substack, subtract the first frame before taking the 
        z projection

    add_first_frame : bool
        Add the unaltered first frame of the stack back to the stack
        before taking z projection. Makes it possible to view sharp structures
        in median transformed data

    invert_color : bool
        Set to True if working with dark particles on a light background

    color_series : bool
        Color the time traces


        
    William Gilpin, Vivek Prakash, and Manu Prakash, 2015
    '''

    if 'diff_order' in kwargs:
        diff_order = kwargs['diff_order']
    else:
        diff_order = 1


    image_files = frames_list
    im_path = os.path.split(image_files[0])[:-1][0]

    frame0 = imread2(image_files[0])

    if len(frame0.shape)==3:
        rgb_flag=True
        frame0 = sum(frame0, axis=2)/3.
    else:
        rgb_flag=False

    # preallocate storage array
    if rgb_flag:
        stack_shape = frame0.shape+(3,)+(frames_to_merge,)
    else:
        stack_shape = frame0.shape+(frames_to_merge,)
    stack = zeros(stack_shape)


    for ii in range(len(image_files)-frames_to_merge):

        if ii == 0:    
            for jj in range(frames_to_merge):
                im = imread2(image_files[jj])
                stack[...,jj] = im
        else:
            if rgb_flag:
                stack = roll(stack, -1, axis=3)
            else:
                stack = roll(stack, -1, axis=2)
            im = imread2(image_files[ii+frames_to_merge])
            stack[...,-1] = im

        stack2 = stack.copy()


        if 'subtract_first' in kwargs:
            if kwargs['subtract_first']:
                front_im = stack2[...,0]
                stack2 = stack2-front_im[..., newaxis]
        if 'subtract_median' in kwargs:
            if kwargs['subtract_median']:
                med_im= median(stack2, axis=-1)
                stack2 = stack2-med_im[..., newaxis]
        if 'take_diff' in kwargs:
            if kwargs['take_diff']:
                stack2 = diff(stack2, n=diff_order, axis=-1)

        if 'add_first_frame' in kwargs:        
            if kwargs['add_first_frame']:
                stack2 = dstack([stack2, stack[...,0]])
        
        if 'color_series' in kwargs:
            if kwargs['color_series']:

                # probably want to preallocate this upstream (255, 204, 153)
                # fullcmap = array(cmap1D((0,250,154),(255,20,147), stack2.shape[-1]))/255.
                fullcmap = array(cmap1D((90, 10, 250),(255, 153, 0),stack2.shape[-1]))/255.

                rvals, gvals, bvals = stack2*fullcmap[:, 0], stack2*fullcmap[:, 1], stack2*fullcmap[:, 2]
                stack2 = concatenate([rvals[...,newaxis],gvals[...,newaxis],bvals[...,newaxis]],axis=-1)
                stack2 = swapaxes(stack2,-1,-2)


        if 'invert_color' in kwargs:
            if 'color_series' in kwargs:
                warnings.warn("Be careful when enabling time series coloring with images with light backgrounds")
            if kwargs['invert_color']:
                max_proj = stack2.min(axis=-1)
                max_proj = 255 - max_proj

            else:
                max_proj = stack2.max(axis=-1)
        else:
            max_proj = stack2.max(axis=-1)


        im_name = os.path.split(image_files[ii])[-1][:-4]

        savestr = out_dir +'/'+im_name+'_streamlines'+'_frames'+str(frames_to_merge)+'.png'

        # This makes it difficult to save with a light background, and it also might cause flickering
        # due to re-normalization
        toimage(max_proj, cmin=0.0, cmax=max(ravel(max_proj))).save(savestr)
Ejemplo n.º 8
0
def overlay_images(dir1, dir2, out_dir, ftype1='.png', ftype2='.png'):
    '''
    Given two directories full of images, load one image from each directory and 
    overlay it on the other with the specified tint and color

    Parameters
    ----------

    dir1 : str
        Path to the directory of images that will be used as the background

    dir2 : str
        Path to the directory of images that will be tinted and overlaid

    out_dir : str
        Path to the directory at which output will be saved

    '''

    bg_ims = glob.glob(dir1 + '/*' + ftype1)
    fg_ims = glob.glob(dir2 + '/*' + ftype2)
    bg_color = (153 / 255., 204 / 255., 255 / 255.)
    fg_color = (255 / 255., 204 / 255., 102 / 255.)

    if len(bg_ims) != len(bg_ims):
        warnings.warn(
            "The two image directories contain different numbers of images.")

    for ind, bg_im in enumerate(bg_ims):

        fg_im = fg_ims[ind]
        im1 = imread2(bg_im)
        if len(im1.shape) == 3:
            im1 = sum(im1, axis=2) / 3.

        im2 = imread2(fg_im)
        if len(im2.shape) == 3:
            im2 = sum(im2, axis=2) / 3.

        im2_norm = im2.astype(double) / 255.
        im2_mask = im2_norm < .2

        im2_norm[im2_mask] = 0.0
        just_bigger_sizes = im2_norm * im1
        just_bigger_sizes = grey_dilation(just_bigger_sizes, size=(2, 2))

        im2_norm = im2.astype(double) / 255.
        #         im2_mask = im2_norm > .2
        im2_norm[~im2_mask] = 0.0
        just_smaller_sizes = im2_norm * im1

        just_smaller_sizes = grey_dilation(just_smaller_sizes, size=(2, 2))

        if ind == 0:
            norm_factor1 = max(ravel(just_smaller_sizes))
            norm_factor2 = max(ravel(just_bigger_sizes))
        just_smaller_sizes = (just_smaller_sizes.astype(double) /
                              norm_factor1) * 255
        just_bigger_sizes = (just_bigger_sizes.astype(double) /
                             norm_factor2) * 255

        rgb_bg = concatenate([(just_smaller_sizes * chan)[..., newaxis]
                              for chan in bg_color],
                             axis=-1)

        rgb_img = concatenate([(just_bigger_sizes * chan)[..., newaxis]
                               for chan in fg_color],
                              axis=-1)

        finim = rgb_bg + rgb_img

        bg_name = os.path.split(bg_im)[-1][:-4]
        fg_name = os.path.split(fg_im)[-1][:-4]
        savestr = out_dir + '/' + bg_name + '_times_' + fg_name + '.png'

        if ind == 0:
            cmax0 = max(ravel(finim))
        toimage(finim, cmin=0.0, cmax=cmax0).save(savestr)
Ejemplo n.º 9
0
def sliding_zproj_internal(frames_list, frames_to_merge, out_dir, **kwargs):
    '''
    This code is optimized for computers that DO NOT have enough 
    RAM to store all the images in memory, but which DO have enough 
    RAM to store an entire z-projection stack in memory
    
    Parameters
    ----------
    frames_list : list of str
        list of image files
        
    frames_to_merge : int
        The number of frames to merge to form a single streamline image
    
    out_dir : str
        path to directory where streamline files are saved
        
    take_diff : bool
        whether to take the difference of consecutive frames
    
    diff_order : int
        the order of the difference in frames when take_diff is used

    subtract_median : bool
        For each substack, subtract the median before taking the 
        z projection

    subtract_first : bool
        For each substack, subtract the first frame before taking the 
        z projection

    add_first_frame : bool
        Add the unaltered first frame of the stack back to the stack
        before taking z projection. Makes it possible to view sharp structures
        in median transformed data

    invert_color : bool
        Set to True if working with dark particles on a light background

    color_series : bool
        Color the time traces


        
    William Gilpin, Vivek Prakash, and Manu Prakash, 2015
    '''

    if 'diff_order' in kwargs:
        diff_order = kwargs['diff_order']
    else:
        diff_order = 1

    image_files = frames_list
    im_path = os.path.split(image_files[0])[:-1][0]

    frame0 = imread2(image_files[0])

    if len(frame0.shape) == 3:
        rgb_flag = True
        frame0 = sum(frame0, axis=2) / 3.
    else:
        rgb_flag = False

    # preallocate storage array
    if rgb_flag:
        stack_shape = frame0.shape + (3, ) + (frames_to_merge, )
    else:
        stack_shape = frame0.shape + (frames_to_merge, )
    stack = zeros(stack_shape)

    for ii in range(len(image_files) - frames_to_merge):

        if ii == 0:
            for jj in range(frames_to_merge):
                im = imread2(image_files[jj])
                stack[..., jj] = im
        else:
            if rgb_flag:
                stack = roll(stack, -1, axis=3)
            else:
                stack = roll(stack, -1, axis=2)
            im = imread2(image_files[ii + frames_to_merge])
            stack[..., -1] = im

        stack2 = stack.copy()

        if 'subtract_first' in kwargs:
            if kwargs['subtract_first']:
                front_im = stack2[..., 0]
                stack2 = stack2 - front_im[..., newaxis]
        if 'subtract_median' in kwargs:
            if kwargs['subtract_median']:
                med_im = median(stack2, axis=-1)
                stack2 = stack2 - med_im[..., newaxis]
        if 'take_diff' in kwargs:
            if kwargs['take_diff']:
                stack2 = diff(stack2, n=diff_order, axis=-1)

        if 'add_first_frame' in kwargs:
            if kwargs['add_first_frame']:
                stack2 = dstack([stack2, stack[..., 0]])

        if 'color_series' in kwargs:
            if kwargs['color_series']:

                # probably want to preallocate this upstream (255, 204, 153)
                # fullcmap = array(cmap1D((0,250,154),(255,20,147), stack2.shape[-1]))/255.
                fullcmap = array(
                    cmap1D((90, 10, 250),
                           (255, 153, 0), stack2.shape[-1])) / 255.

                rvals, gvals, bvals = stack2 * fullcmap[:,
                                                        0], stack2 * fullcmap[:,
                                                                              1], stack2 * fullcmap[:,
                                                                                                    2]
                stack2 = concatenate([
                    rvals[..., newaxis], gvals[..., newaxis], bvals[...,
                                                                    newaxis]
                ],
                                     axis=-1)
                stack2 = swapaxes(stack2, -1, -2)

        if 'invert_color' in kwargs:
            if 'color_series' in kwargs:
                warnings.warn(
                    "Be careful when enabling time series coloring with images with light backgrounds"
                )
            if kwargs['invert_color']:
                max_proj = stack2.min(axis=-1)
                max_proj = 255 - max_proj

            else:
                max_proj = stack2.max(axis=-1)
        else:
            max_proj = stack2.max(axis=-1)

        im_name = os.path.split(image_files[ii])[-1][:-4]

        savestr = out_dir + '/' + im_name + '_streamlines' + '_frames' + str(
            frames_to_merge) + '.png'

        # This makes it difficult to save with a light background, and it also might cause flickering
        # due to re-normalization
        toimage(max_proj, cmin=0.0, cmax=max(ravel(max_proj))).save(savestr)