import platform
if platform.uname()[1] == "RDP-M7520-JL":
    base_dir = '/data/Meristems/Carlos/SuperResolution/'
elif platform.uname()[1] == "calculus":
    base_dir = '/projects/SamMaps/SuperResolution/LSM Airyscan/'
else:
    raise ValueError("Unknown custom path to 'base_dir' for this system...")

fname = 'SAM1-gfp-pi-stack-LSM800-Airyscan Processing-high_PI_conf_z-stack_reg.tif'
base_fname, ext = splitext(fname)
image = imread(base_dir + fname)

iso_image = isometric_resampling(image, method='min', option='cspline')
iso_image.shape

iso_image = z_slice_contrast_stretch(iso_image, pc_min=1.5)
iso_image = linear_filtering(iso_image,
                             method="gaussian_smoothing",
                             sigma=0.1,
                             real=True)

# xsh, ysh, zsh = iso_image.shape
# mid_x, mid_y, mid_z = int(xsh/2.), int(ysh/2.), int(zsh/2.)
#
# selected_hmin = profile_hmin(iso_image, x=mid_x, z=mid_z, plane='x', zone=mid_z)

for selected_hmin in np.arange(4000, 6000, 500):
    seg_im = auto_seeded_watershed(iso_image, selected_hmin, control='most')
    # np.unique(seg_im)

    seg_fname = base_fname + "-seg_hmin{}{}".format(selected_hmin, ext)
Exemple #2
0
from timagetk.algorithms.resample import resample
from timagetk.algorithms.resample import isometric_resampling

from timagetk.algorithms.exposure import z_slice_contrast_stretch
from timagetk.algorithms.exposure import z_slice_equalize_adapthist

raw_img = imread("/data/GabriellaMosca/EM_C_140/EM_C_140- C=0.tif")
h_min = 2
sigma = 1.5

# raw_img = imread("/data/GabriellaMosca/EM_C_214/EM_C_214 C=0.tif")

print "\n - Performing z-slices adaptative histogram equalisation on the intensity image to segment..."
eq_img1 = z_slice_equalize_adapthist(raw_img)
print "\n - Performing z-slices histogram contrast stretching on the intensity image to segment..."
eq_img2 = z_slice_contrast_stretch(raw_img)

from timagetk.visu.mplt import grayscale_imshow
grayscale_imshow([
    raw_img.get_z_slice(85),
    eq_img1.get_z_slice(85),
    eq_img2.get_z_slice(85)
],
                 img_title=['Original', "AHE", 'CS'])

img2seg = eq_img2

print "\n - Automatic seed detection...".format(h_min)
print " -- Gaussian smoothing with std_dev={}...".format(sigma)
smooth_img = linear_filtering(img2seg,
                              sigma=sigma,
def seg_pipe(img2seg,
             h_min,
             img2sub=None,
             iso=True,
             equalize=True,
             stretch=False,
             std_dev=0.8,
             min_cell_volume=20.,
             back_id=1,
             to_8bits=False):
    """Define the sementation pipeline

    Parameters
    ----------
    img2seg : str
        image to segment.
    h_min : int
        h-minima used with the h-transform function
    img2sub : str, optional
        image to subtract to the image to segment.
    iso : bool, optional
        if True (default), isometric resampling is performed after h-minima
        detection and before watershed segmentation
    equalize : bool, optional
        if True (default), intensity adaptative equalization is performed before
        h-minima detection
    stretch : bool, optional
        if True (default, False), intensity histogram stretching is performed
        before h-minima detection
    std_dev : float, optional
        real unit standard deviation used for Gaussian smoothing of the image to segment
    min_cell_volume : float, optional
        minimal volume accepted in the segmented image
    back_id : int, optional
        the background label
    to_8bits : bool, optional
        transform the image to segment as an unsigned 8 bits image for the h-transform
        and seed-labelleing steps

    Returns
    -------
    seg_im : SpatialImage
        the labelled image obtained by seeded-watershed

    Notes
    -----
      * Both 'equalize' & 'stretch' can not be True at the same time since they work
        on the intensity of the pixels;
      * Signal subtraction is performed after intensity rescaling (if any);
      * Linear filtering (Gaussian smoothing) is performed before h-minima transform
        for local minima detection;
      * Gaussian smoothing should be performed on isometric images, if the provided
        image is not isometric, we resample it before smoothing, then go back to
        original voxelsize;
      * In any case H-Transfrom is performed on the image with its native resolution
        to speed upd seed detection;
      * Same goes for connexe components detection (seed labelling);
      * Segmentation will be performed on the isometric images if iso is True, in
        such case we resample the image of detected seeds and use the isometric
        smoothed intensity image;
    """
    t_start = time.time()
    # - Check we have only one intensity rescaling method called:
    try:
        assert equalize + stretch < 2
    except AssertionError:
        raise ValueError(
            "Both 'equalize' & 'stretch' can not be True at once!")
    # - Check the standard deviation value for Gaussian smoothing is valid:
    try:
        assert std_dev <= 1.
    except AssertionError:
        raise ValueError(
            "Standard deviation for Gaussian smoothing should be superior or equal to 1!"
        )

    ori_vxs = img2seg.voxelsize
    ori_shape = img2seg.shape

    if img2sub is not None:
        print "\n - Performing signal substraction..."
        img2seg = signal_subtraction(img2seg, img2sub)

    if equalize:
        print "\n - Performing z-slices adaptative histogram equalisation on the intensity image to segment..."
        img2seg = z_slice_equalize_adapthist(img2seg)
    if stretch:
        print "\n - Performing z-slices histogram contrast stretching on the intensity image to segment..."
        img2seg = z_slice_contrast_stretch(img2seg)

    print "\n - Automatic seed detection...".format(h_min)
    # morpho_radius = 1.0
    # asf_img = morphology(img2seg, max_radius=morpho_radius, method='co_alternate_sequential_filter')
    # ext_img = h_transform(asf_img, h=h_min, method='h_transform_min')
    min_vxs = min(img2seg.voxelsize)
    if std_dev < min_vxs:
        print " -- Isometric resampling prior to Gaussian smoothing...".format(
            std_dev)
        img2seg = isometric_resampling(img2seg)

    print " -- Gaussian smoothing with std_dev={}...".format(std_dev)
    iso_smooth_img = linear_filtering(img2seg,
                                      std_dev=std_dev,
                                      method='gaussian_smoothing',
                                      real=True)

    if std_dev < min_vxs:
        print " -- Down-sampling a copy back to original voxelsize (to use with `h-transform`)..."
        smooth_img = resample(iso_smooth_img, ori_vxs)
        if not np.allclose(ori_shape, smooth_img.shape):
            print "WARNING: shape missmatch after down-sampling from isometric image:"
            print " -- original image shape: {}".format(ori_shape)
            print " -- down-sampled image shape: {}".format(smooth_img.shape)
    else:
        print " -- Copying original image (to use with `h-transform`)..."
        smooth_img = iso_smooth_img

    if not iso:
        del iso_smooth_img  # no need to keep this image after this step!

    print " -- H-minima transform with h-min={}...".format(h_min)
    if to_8bits:
        ext_img = h_transform(smooth_img.to_8bits(),
                              h=h_min,
                              method='h_transform_min')
    else:
        ext_img = h_transform(smooth_img, h=h_min, method='h_transform_min')
    if iso:
        smooth_img = iso_smooth_img  # no need to keep both images after this step!

    print " -- Region labelling: connexe components detection..."
    seed_img = region_labeling(ext_img,
                               low_threshold=1,
                               high_threshold=h_min,
                               method='connected_components')
    print "Detected {} seeds!".format(len(np.unique(seed_img)) -
                                      1)  # '0' is in the list!
    del ext_img  # no need to keep this image after this step!

    print "\n - Performing seeded watershed segmentation..."
    if iso:
        seed_img = isometric_resampling(seed_img, option='label')
    if to_8bits:
        seg_im = segmentation(smooth_img.to_8bits(),
                              seed_img,
                              method='seeded_watershed')
    else:
        seg_im = segmentation(smooth_img, seed_img, method='seeded_watershed')
    # seg_im[seg_im == 0] = back_id
    print "Detected {} labels!".format(len(np.unique(seg_im)))

    if min_cell_volume > 0.:
        from vplants.tissue_analysis.spatial_image_analysis import SpatialImageAnalysis
        print "\n - Performing cell volume filtering..."
        spia = SpatialImageAnalysis(seg_im, background=None)
        vol = spia.volume()
        too_small_labels = [
            k for k, v in vol.items() if v < min_cell_volume and k != 0
        ]
        if too_small_labels != []:
            print "Detected {} labels with a volume < {}µm2".format(
                len(too_small_labels), min_cell_volume)
            print " -- Removing seeds leading to small cells..."
            spia = SpatialImageAnalysis(seed_img, background=None)
            seed_img = spia.get_image_without_labels(too_small_labels)
            print " -- Performing final seeded watershed segmentation..."
            seg_im = segmentation(smooth_img,
                                  seed_img,
                                  method='seeded_watershed')
            # seg_im[seg_im == 0] = back_id
            print "Detected {} labels!".format(len(np.unique(seg_im)))

    print "\nDone in {}s".format(round(time.time() - t_start, 3))
    return seg_im
Exemple #4
0
from timagetk.io import imread
from timagetk.algorithms.exposure import z_slice_contrast_stretch
from timagetk.algorithms.resample import isometric_resampling
from timagetk.plugins import linear_filtering
from timagetk.plugins.segmentation import auto_seeded_watershed
from timagetk.visu.mplt import profile_hmin

from skimage import img_as_float
from skimage.color import label2rgb, gray2rgb

int_img = imread(data_path('p58-t0-a0.lsm'))
print int_img.shape
print int_img.voxelsize

int_img = isometric_resampling(int_img, method='min', option='cspline')
int_img = z_slice_contrast_stretch(int_img, pc_min=1)
int_img = linear_filtering(int_img,
                           method="gaussian_smoothing",
                           sigma=0.25,
                           real=True)

xsh, ysh, zsh = int_img.shape
mid_x, mid_y, mid_z = int(xsh / 2.), int(ysh / 2.), int(zsh / 2.)

h_min = profile_hmin(int_img, x=mid_x, z=mid_z, plane='x', zone=mid_z)

seg_img = auto_seeded_watershed(int_img, hmin=h_min)
print seg_img.shape

label_rgb = label2rgb(seg_img, alpha=1, bg_label=1, bg_color=(0, 0, 0))
print label_rgb.shape
Exemple #5
0
else:
    raise ValueError("Unknown custom path to 'base_dir' for this system...")

fname = '20180616 3-global della_Ler_LD +++.lsm'

from timagetk.io import imread
im = imread(join(base_dir, fname))

from timagetk.plugins import linear_filtering
from timagetk.algorithms.exposure import z_slice_contrast_stretch
from timagetk.algorithms.exposure import z_slice_equalize_adapthist
s = 0.6

smooth = linear_filtering(im, method="gaussian_smoothing", sigma=s, real=True)

stretch = z_slice_contrast_stretch(im)
smooth_str = z_slice_contrast_stretch(
    linear_filtering(im, method="gaussian_smoothing", sigma=s, real=True))
str_smooth = linear_filtering(z_slice_contrast_stretch(im),
                              method="gaussian_smoothing",
                              sigma=s,
                              real=True)

eq = z_slice_equalize_adapthist(im)
smooth_eq = z_slice_equalize_adapthist(
    linear_filtering(im, method="gaussian_smoothing", sigma=s, real=True))
eq_smooth = linear_filtering(z_slice_equalize_adapthist(im),
                             method="gaussian_smoothing",
                             sigma=s,
                             real=True)