コード例 #1
0
from timagetk.plugins import auto_seeded_watershed
from timagetk.visu.mplt import profile_hmin

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')
コード例 #2
0
ファイル: test_label2rgb.py プロジェクト: gcerutti/SamMaps
from timagetk.util import data_path
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))
コード例 #3
0
ファイル: crop_image.py プロジェクト: gcerutti/SamMaps
            assert all([vxs[n] == ref_vxs for vxs in vxs_list])
        except:
            raise ValueError(
                "Voxelsize missmatch along axis {} ({}) among list of images!".
                format(axis[n], n))

for im2crop_fname in im2crop_fnames:
    print "\n\n# - Reading image file {}...".format(im2crop_fname)
    im2crop = read_image(im2crop_fname)
    print "Done."
    # - Create output filename:
    out_fname = splitext_zip(im2crop_fname)[0]
    # - Performs isometric resampling if required:
    if iso:
        out_fname += '-iso'
        im2crop = isometric_resampling(im2crop)
    # - Get original image infos:
    shape, ori, vxs, md = get_infos(im2crop)
    print "\nGot original shape: {}".format(shape)
    print "Got original voxelsize: {}".format(vxs)
    # - Crop the image:
    bounding_box = []
    for n in range(ndim):
        bounding_box.extend([lower_bounds[n], upper_bounds[n]])
    im = crop_image(im2crop, bounding_box)
    # - Add cropping region to filename:
    for n, ax in enumerate(axis):
        if lower_bounds[n] != 0 or upper_bounds[n] != -1:
            out_fname += '-{}{}_{}'.format(ax, lower_bounds[n],
                                           upper_bounds[n])
コード例 #4
0
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