Exemplo n.º 1
0
def compute_fluorescence_info(image, mask, f_in, f_ma, prop, parent_folder=''):

    if image is None:
        # load image
        path_to_file = os.path.join(parent_folder, f_in)
        image = imread(path_to_file)
        if image.ndim == 2:
            image = np.expand_dims(image, 0)
        if image.shape[-1] == np.min(image.shape):
            image = np.moveaxis(image, -1, 0)
        image = np.stack(
            [img[prop['slice']].astype(np.float) for img in image])

    if mask is None:
        # load mask
        path_to_mask = os.path.join(parent_folder, f_ma)
        mask = img_as_bool(
            imread(path_to_mask)[prop['slice']].astype(np.float))

    # make sure the input image is a 3D numpy array even if it has only one channel
    N_ch = image.shape[0]

    # setup the dictionary
    dict_ = {}
    dict_['input_file'] = prop['input_file']
    dict_['mask_file'] = prop['mask_file']
    for ch in range(N_ch):
        dict_['ch%d_APprofile' % ch] = []
        dict_['ch%d_LRprofile' % ch] = []
        dict_['ch%d_RADprofile' % ch] = []
        dict_['ch%d_ANGprofile' % ch] = []
        dict_['ch%d_Background' % ch] = []
        dict_['ch%d_Average' % ch] = []

    # compute meshgrid if not computed in the previous step already
    tangent = prop['tangent']
    midline = prop['midline']
    width = prop['meshgrid_width']
    mesh = prop['meshgrid']
    if mesh == None:
        mesh = meshgrid.compute_meshgrid(midline, tangent, width)

    for ch in range(N_ch):
        fl = image[ch]
        # compute average and background in the current channel
        dict_['ch%d_Background' % ch] = np.mean(fl[mask == 0])
        dict_['ch%d_Average' % ch] = np.mean(fl[mask])

        # compute meshgrid and straighten
        ap, lr, rad, ang = computeprofiles.compute_profiles_fluo(
            fl, mask, mesh, visualize=False)
        for j, v in enumerate(ap):
            if not np.isfinite(v):
                ap[j] = 0
        # make the nans equal to the first or last finite element
        left = np.array(ap)[np.array(ap) > 0][0]
        right = np.array(ap)[np.array(ap) > 0][-1]
        for j, v in enumerate(ap):
            if v == 0 and (j < (len(ap) / 2)):
                ap[j] = left
            if v == 0 and (j > (len(ap) / 2)):
                ap[j] = right

        dict_['ch%d_APprofile' % ch] = ap
        dict_['ch%d_LRprofile' % ch] = lr
        dict_['ch%d_RADprofile' % ch] = rad
        dict_['ch%d_ANGprofile' % ch] = ang

        # transform the sub dictionary into a dataframe
        # dict_['ch%d'%ch] = pd.Series(dict_['ch%d'%ch])

    return pd.Series(dict_)
Exemplo n.º 2
0
def compute_morphological_info(mask,
                               f_in,
                               f_ma,
                               down_shape,
                               compute_meshgrid=False,
                               compute_locoefa=True,
                               keys=[
                                   'centroid',
                                   'slice',
                                   'area',
                                   'eccentricity',
                                   'major_axis_length',
                                   'minor_axis_length',
                                   'equivalent_diameter',
                                   'perimeter',
                                   'euler_number',
                                   'extent',
                                   'inertia_tensor',
                                   'inertia_tensor_eigvals',
                                   'moments',
                                   'moments_central',
                                   'moments_hu',
                                   'moments_normalized',
                                   'orientation',
                               ]):

    if mask is None:
        # load mask
        mask = img_as_bool(imread(f_ma).astype(float))

    # print(f_in)
    # label mask
    labeled_mask, _ = label(mask)
    # compute morphological info
    props = measure.regionprops(labeled_mask)
    dict_ = {}
    for key in keys:
        dict_[key] = props[0][key]

    dict_['form_factor'] = dict_['perimeter']**2 / (4 * np.pi * dict_['area'])

    ## append file info that come as input and are not computed by default
    dict_['input_file'] = os.path.split(f_in)[1]
    dict_['mask_file'] = os.path.join('result_segmentation',
                                      os.path.split(f_ma)[1])

    ### compute the anchor points, spline, midline and meshgrid (optional)
    bf = imread(f_in)
    if len(bf.shape) == 2:
        bf = np.expand_dims(bf, 0)
    if bf.shape[-1] == np.min(bf.shape):
        bf = np.moveaxis(bf, -1, 0)
    bf = bf[0][dict_['slice']]
    ma = mask[dict_['slice']]
    anch = anchorpoints.compute_anchor_points(mask, dict_['slice'], down_shape)

    N_points, tck = spline.compute_spline_coeff(ma, bf, anch)

    diagonal = int(np.sqrt(ma.shape[0]**2 + ma.shape[1]**2) / 2)
    mid, tangent, width = midline.compute_midline_and_tangent(
        anch, N_points, tck, diagonal)
    mesh = None
    if compute_meshgrid:
        mesh = meshgrid.compute_meshgrid(mid, tangent, width)

    # store all these info in the dicionary
    dict_['anchor_points_midline'] = anch
    dict_['N_points_midline'] = N_points
    dict_['tck'] = tck
    dict_['midline'] = mid
    dict_['tangent'] = tangent
    dict_['meshgrid_width'] = width
    dict_['meshgrid'] = mesh
    if compute_locoefa:
        dict_['locoefa_coeff'] = computecoeff.compute_LOCOEFA_Lcoeff(
            mask, down_shape).locoefa_coeff.values
    else:
        dict_['locoefa_coeff'] = 0.

    return pd.Series(dict_)
Exemplo n.º 3
0
                image = imread(os.path.join(parent_folder, image_folder, f_in))
                image = np.stack(
                    [img[_slice].astype(np.float) for img in image])
                bckg = df_fluo.ch1_Background[i]
                image[1] = image[1].astype(float) - bckg
                image[1] = np.clip(image[1], 0, None)
                mask = imread(os.path.join(parent_folder, image_folder,
                                           f_ma))[_slice]

                # compute the meshgrid
                tangent = df_morpho.tangent[i]
                midline = df_morpho.midline[i]
                width = df_morpho.meshgrid_width[i]
                mesh = df_morpho.meshgrid[i]
                if mesh == None:
                    mesh = meshgrid.compute_meshgrid(midline, tangent, width)

                # straighten the mask and the image
                mesh_shape = mesh.shape
                coords_flat = np.reshape(mesh,
                                         (mesh_shape[0] * mesh_shape[1], 2)).T

                ma_straight = map_coordinates(mask,
                                              coords_flat,
                                              order=0,
                                              mode='constant',
                                              cval=0).T
                ma_straight = np.reshape(ma_straight,
                                         (mesh_shape[0], mesh_shape[1]))

                fl_straight = map_coordinates(image[1],
Exemplo n.º 4
0
def compute_straight_morphological_info(mask,
                                        f_in,
                                        f_ma,
                                        down_shape,
                                        prop,
                                        parent_folder='',
                                        compute_locoefa=True,
                                        keys=[
                                            'centroid',
                                            'slice',
                                            'area',
                                            'eccentricity',
                                            'major_axis_length',
                                            'minor_axis_length',
                                            'equivalent_diameter',
                                            'perimeter',
                                            'euler_number',
                                            'extent',
                                            'inertia_tensor',
                                            'inertia_tensor_eigvals',
                                            'moments',
                                            'moments_central',
                                            'moments_hu',
                                            'moments_normalized',
                                            'orientation',
                                        ]):
    if mask is None:
        # load mask
        path_to_mask = os.path.join(parent_folder, f_ma)
        mask = img_as_bool(
            imread(path_to_mask)[prop['slice']].astype(np.float))

    # compute meshgrid if not computed in the previous step already
    tangent = prop['tangent']
    midline = prop['midline']
    width = prop['meshgrid_width']
    mesh = prop['meshgrid']
    if mesh == None:
        mesh = meshgrid.compute_meshgrid(midline, tangent, width)

    # straighten the mask
    ma_straight = np.reshape(
        map_coordinates(mask,
                        np.reshape(mesh, (mesh.shape[0] * mesh.shape[1], 2)).T,
                        order=0,
                        mode='constant',
                        cval=0).T, (mesh.shape[0], mesh.shape[1]))

    # label straighetned mask
    labeled_mask, _ = label(ma_straight)

    # keep only larger object
    ma_straight = (labeled_mask == (
        np.bincount(labeled_mask.flat)[1:].argmax() + 1))
    labeled_mask, _ = label(ma_straight)

    # compute morphological info
    props = measure.regionprops(labeled_mask)
    dict_ = {}
    for key in keys:
        dict_[key] = props[0][key]

    dict_['form_factor'] = dict_['perimeter']**2 / (4 * np.pi * dict_['area'])

    # append info that are not computed by default
    dict_['input_file'] = os.path.split(f_in)[1]
    dict_['mask_file'] = os.path.join('result_segmentation',
                                      os.path.split(f_ma)[1])
    if compute_locoefa:
        dict_['locoefa_coeff'] = computecoeff.compute_LOCOEFA_Lcoeff(
            ma_straight, down_shape).locoefa_coeff.values
    else:
        dict_['locoefa_coeff'] = 0.

    return pd.Series(dict_)
Exemplo n.º 5
0
def generate_meshgrid_img_cropped(input_folder, keep_open=True):
    print('### Generating recap meshgrid image at', input_folder)
    _, cond = os.path.split(input_folder)
    segment_folder = os.path.join(input_folder, 'result_segmentation')

    file_extension = '_morpho_params.json'
    fname = os.path.join(segment_folder, cond + file_extension)
    if not os.path.exists(fname):
        props = computemorphology.compute_morphological_info(input_folder)
        ioMorph.save_morpho_params(segment_folder, cond, props)
    else:
        props = ioMorph.load_morpho_params(segment_folder, cond)

    flist_in = [os.path.join(input_folder, i) for i in props['input_file']]
    flist_ma = [os.path.join(input_folder, i) for i in props['mask_file']]

    n_img = len(flist_in)
    ncols = 5
    nrows = (n_img - 1) // 5 + 1

    fig, ax = plt.subplots(figsize=(3 * ncols, 3 * nrows),
                           nrows=nrows,
                           ncols=ncols)
    plt.subplots_adjust(top=0.95,
                        left=0.05,
                        right=0.95,
                        bottom=0.05,
                        hspace=0.01,
                        wspace=0.01)
    ax = ax.flatten()

    for i in tqdm.tqdm(range(n_img)):
        prop = {key: props[key][i] for key in props}

        tangent = prop['tangent']
        midline = prop['midline']
        width = prop['meshgrid_width']
        mesh = prop['meshgrid']
        if not mesh:
            mesh = meshgrid.compute_meshgrid(midline, tangent, width)
        anch = prop['anchor_points_midline']

        bf = imread(flist_in[i])
        if len(bf.shape) == 2:
            bf = np.expand_dims(bf, 0)
        if bf.shape[-1] == np.min(bf.shape):
            bf = np.moveaxis(bf, -1, 0)
        bf = bf[0][prop['slice']]
        ma = img_as_bool(imread(flist_ma[i])[prop['slice']].astype(np.float))

        meshgrid.visualize_meshgrid(midline,
                                    tangent,
                                    mesh,
                                    bf,
                                    color='white',
                                    ax=ax[i])

        ax[i].contour(ma, [0.5], colors='r', alpha=.5)
        ax[i].plot(anch[:, 1], anch[:, 0], '-or', lw=.5, ms=.5, alpha=.5)

        name = os.path.split(flist_in[i])[-1]
        ax[i].set_title(("\n".join(wrap(name, 20))), fontsize=6)

    for a in ax:
        a.axis('off')
    for j in range(i + 1, len(ax)):
        ax[j].remove()

    fig.show()

    print('### Saving image...')
    # save figure
    fig.savefig(os.path.join(segment_folder, cond + '_meshgrid_recap.png'),
                dpi=300)
    if not keep_open:
        plt.close(fig)
    print('### Done saving!')