コード例 #1
0
ファイル: analysis.py プロジェクト: vstadnytskyi/lcp-video
def label(input):
    """
    customized label function that mimics functionality of label functions in scipy and skimage (see below)

    the first axis(fast axis) is concidered as fast axis as in numpy definitions.

    scipy.ndimage.label
    skimage.measure.label https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.label
    """
    N_spot_max = 0
    length = input.shape[0]
    for i in range(1,length):
        prev_mask = fmask['mask'][i-1]
        prev_emask = femask['emask'][i-1]
        mask = fmask['mask'][i]
        #create new enumarated mask
        emask = label(mask,ones((3,3),bool))[0]
        N_spot_max += emask.max()
        #take care of overlapping contiguious spots by assigning them to a number from previous frame.
        idx = where(emask != 0)
        emask[idx] += N_spot_max
        temp_mask = grow_mask(prev_mask,1)*mask
        temp_label = label(temp_mask,ones((3,3),bool))[0]

        # Compute overlaps with the previous emask.

        #Grow emasks by M(default 1) and get indices of overlapping seciton. Multiplication of masks returns only pixels that are non-zero in both masks.
        prev_emask_g =grow_mask(prev_emask,1)
        emask_g = grow_mask(emask,1)
        indices = where(emask1_g*emask2_g > 0)

        #obtain unique values and indices
        values_u, idx_u = np.unique(emask_g[indices], return_index = True)

        #construct a set of unique indices
        indices_u = (indices[0][idx_u],indices[1][idx_u])

        #replace values in emask with values in prev_emask
        for i in range(values_u.shape[0]):
            r = indices_u[0][i]
            c = indices_u[1][i]
            idxs = where(emask2 == emask_g[r,c])
            emask[idxs] = prev_emask_g[r,c]

        #save emask to hdf5file
        femask['emask'][i] = emask
        femask['spots'][i] = emask.max()
コード例 #2
0
def get_dpeaks_s_coeff_d0_zero(dpeaks):
    """
    get selector for a given particle

    """
    THREASHOLD = 6
    ROI_EXTRA = 20

    import numpy as np
    from lcp_video.analysis import grow_mask
    from lcp_video import peaks_files

    import h5py

    select = (dpeaks['d0'] == 0)*(dpeaks['Mp'] > 0)
    indices = np.where(select)
    peak_ids = np.where(select)
    intensity = np.where(select)[0]*np.nan
    peaks_list = list(peak_ids[0])
    for i in range(len(peaks_list)):
        roi = dpeaks['roi'][peaks_list[i]]
        mask = grow_mask(roi > THREASHOLD,1)
        intensity[i] = (roi*mask).sum()


    frames = dpeaks['frame'][selector]
    M0 = dpeaks['M0'][selector]
    (unique,count) = np.unique(frames, return_counts=True)
    intensity = unique*0.0
    coeff = unique*0.0
    s_coeff = frames*0.0

    for frame in list(frames):
        index = list(unique).index(frame)
        tselector = selector*(dpeaks['frame']==frame)
        image, image_fit, X, Y, Z = peaks_files.image_from_selects(dpeaks,[tselector])
        img = image[int(np.min(Z)-ROI_EXTRA):int(np.max(Z)+ROI_EXTRA),int(np.min(X)-ROI_EXTRA):int(np.max(X)+ROI_EXTRA)]
        mask = grow_mask(img > THREASHOLD,1)
        intensity[index] = (img*mask).sum()
        coeff[index] = (count[index])*(1/51.2)

    for i in range(len(frames)):
        index = list(unique).index(list(frames)[i])
        sss = frames == frames[i]
        s_coeff[i] = coeff[index]*intensity[index]/M0[sss].sum()

    return s_coeff,indices
コード例 #3
0
def get_s_coeff_slow_moving(dpeaks,particle, verbose = False):
    """
    get selector for a given particle
    """
    THREASHOLD = 4
    ROI_EXTRA = 20

    import h5py

    import numpy as np
    from lcp_video.analysis import grow_mask
    from lcp_video import peaks_files
    select = dpeaks['Mp'][()] == particle
    particle_index = np.where(select)[0]
    frames = dpeaks['frame'][particle_index]

    M0 = dpeaks['M0'][particle_index]
    (unique,count) = np.unique(frames, return_counts=True)
    intensity = unique*0.0
    coeff = unique*0.0
    s_coeff = frames*0.0


    for frame in list(unique):
        index = list(unique).index(frame)
        index_frame = particle_index[np.where(frames==frame)[0]]
        if verbose:
            print(f'index_frame {index_frame}')

        image, image_fit, X, Y, Z = peaks_files.image_from_index(dpeaks,[index_frame])

        img = image[np.maximum(0,int(np.min(Z)-ROI_EXTRA)):int(np.max(Z)+ROI_EXTRA),np.maximum(0,int(np.min(X)-ROI_EXTRA)):int(np.max(X)+ROI_EXTRA)]
        mask = grow_mask(img > THREASHOLD,1)
        if verbose:
            print()
            print('Z',np.maximum(np.min(Z)-ROI_EXTRA,0),np.max(Z)+ROI_EXTRA)
            print('X',np.maximum(np.min(X)-ROI_EXTRA,0),np.max(X)+ROI_EXTRA)
            from matplotlib import pyplot as plt
            plt.figure()
            plt.imshow(img)
            print(f'number of hits {mask.sum()}')
        intensity[index] = (img*mask).sum()
        coeff[index] = (count[index])*(1/51.2)
        img*=0.0
    if verbose:
        print(f'intensity {intensity}')
        print(f'coeff {coeff}')
        print(f's_coeff {s_coeff}')
    for i in range(len(frames)):
        index = list(unique).index(list(frames)[i])
        sss = frames == frames[i]
        s_coeff[i] = coeff[index]*intensity[index]/M0[sss].sum()

    return s_coeff,particle_index
コード例 #4
0
ファイル: analysis.py プロジェクト: vstadnytskyi/lcp-video
def maxima_from_image(image, hits, stats, offset = None, footprint = 3):
    """
    finds maxima in the image.
    returns cmax, a boolean numpy array with all maxima.
    """

    from numpy import left_shift, right_shift, ones
    from scipy.ndimage import maximum_filter, median_filter, minimum_filter
    from lcp_video.analysis import grow_mask
    if offset is None:
        offset = offset_image(shape = image.shape)
    image = image*grow_mask(hits,1)
    image_4 = (left_shift(image,4)- offset)*grow_mask(hits,1)
    mxma = maximum_filter(image_4 , footprint = ones((footprint,footprint)))
    bckg_foot = ones((footprint,footprint))
    bckg_foot[1,1] = 0
    flat_foot = ones((footprint,footprint))
    hits_med = right_shift(median_filter((image), footprint = bckg_foot),4)
    hits_max = right_shift(maximum_filter((image), footprint = flat_foot),4)
    mxma_mask = (mxma==image_4)*hits
    res_bckg_med = right_shift(hits_med,4)*mxma_mask
    res_mxma = right_shift(mxma,4)*mxma_mask
    z = (image - hits_med)*hits/stats['var']
    return res_mxma, z
コード例 #5
0
ファイル: analysis.py プロジェクト: vstadnytskyi/lcp-video
def grow_mask(mask,count=1):
    """Expands area where pixels have value=1 by 'count' pixels in each
    direction, including along the diagonal. If count is 1 or omitted a single
    pixel grows to nine pixels.
    """


    if count < 1: return mask
    if count > 1: mask = grow_mask(mask,count-1)
    w,h = mask.shape
    mask2 = zeros((w,h),mask.dtype)
    mask2 |= mask
    mask2[0:w,0:h-1] |= mask[0:w,1:h] # move up by 1 pixel
    mask2[0:w,1:h] |= mask[0:w,0:h-1] # move down by 1 pixel
    mask2[0:w-1,0:h] |= mask[1:w,0:h] # move to the left by 1 pixel
    mask2[1:w,0:h] |= mask[0:w-1,0:h] # move to the right by 1 pixel

    mask2[0:w-1,0:h-1] |= mask[1:w,1:h] # move left and up by 1 pixel
    mask2[0:w-1,1:h] |= mask[1:w,0:h-1] # move left and down by 1 pixel
    mask2[1:w,0:h-1] |= mask[0:w-1,1:h] # move up and up by 1 pixel
    mask2[1:w,1:h] |= mask[0:w-1,0:h-1] # move up and down by 1 pixel

    return mask2
コード例 #6
0
def calculate_spots_from_mask(data_filename, mask_filename, stats_filename,
                              ffcorr_filename):
    """
    creates a catalog(table) of unique particles according to the supplied mask. The
    """
    from time import time, ctime
    import h5py
    from ubcs_auxiliary.save_load_object import load_from_file
    import numpy as np
    import cv2
    import os
    from lcp_video.analysis import grow_mask, get_array_piece

    temp_arr = np.zeros((21, ))
    d_file = h5py.File(data_filename, 'r')
    m_file = h5py.File(mask_filename, 'r')
    stats_data = load_from_file(stats_filename)
    M1 = (stats_data['S1'] - stats_data['Imax1'] -
          stats_data['Imin']) / (stats_data['N'] - 2)
    FFcorr = load_from_file(ffcorr_filename)['FF_corr']
    N_spots = np.sum(m_file['particle_hits'])

    head, tail = os.path.split(data_filename)
    destination_filename = os.path.join(
        head,
        tail.split('.')[0] + '.spots.gzip.hdf5')
    with h5py.File(destination_filename, 'a') as f_destination:
        f_destination.create_dataset('spots', (N_spots, 21),
                                     compression='gzip')
        f_destination.create_dataset('spots_images', (N_spots, 31, 31),
                                     compression='gzip')
        f_destination.create_dataset('stats file', data=stats_filename)
        f_destination.create_dataset('FFcorr file', data=ffcorr_filename)
        f_destination.create_dataset('time', data=ctime(time()))
        spot_i = 0
        for i in range(600):
            print(
                f'{ctime(time())}: processing image {i} and saving into file {f_destination}'
            )
            spots_N = m_file['particle_hits'][i]
            enummask = m_file['particle_mask'][i]
            image = d_file['images'][i] - M1
            t = d_file['timestamp'][i]
            for j in range(spots_N):
                mask = grow_mask((enummask == (j + 1)), 2)
                img = image * mask / FFcorr
                temp_arr[0] = i
                temp_arr[1] = spot_i
                temp_arr[2] = t
                temp_arr[3] = np.max(img)
                temp_arr[4] = np.where(img == temp_arr[3])[1][0]
                temp_arr[5] = np.where(img == temp_arr[3])[0][0]
                temp_arr[6] = np.sum(mask)
                m = cv2.moments(img)
                temp_arr[7] = m['m00']
                temp_arr[8] = m['m10']
                temp_arr[9] = m['m01']
                temp_arr[10] = m['m11']
                temp_arr[11] = m['m20']
                temp_arr[12] = m['m02']
                temp_arr[13] = m['m21']
                temp_arr[14] = m['m12']
                temp_arr[15] = m['m30']
                temp_arr[16] = m['m03']
                x_mean = m['m10'] / m['m00']
                y_mean = m['m01'] / m['m00']
                x_var = (m['m20'] / m['m00']) - (m['m10'] / m['m00'])**2
                y_var = (m['m02'] / m['m00']) - (m['m01'] / m['m00'])**2
                temp_arr[17] = x_mean
                temp_arr[18] = y_mean
                temp_arr[19] = x_var
                temp_arr[20] = y_var
                spots_image = get_array_piece(img,
                                              center=(int(x_mean),
                                                      int(y_mean)),
                                              radius=15)
                f_destination['spots'][spot_i] = temp_arr
                f_destination['spots_images'][spot_i] = spots_image
                spot_i += 1