def test_plugin(): im = imread(data_path('segmentation_src.inr')) im_ref = imread(data_path('segmentation_seeded_watershed.inr')) smooth_img = linear_filtering(im, std_dev=2.0, method='gaussian_smoothing') regext_img = h_transform(smooth_img, h=5, method='h_transform_min') conn_img = region_labeling(regext_img, low_threshold=1, high_threshold=3, method='connected_components') wat_img = segmentation(smooth_img, conn_img, control='first', method='seeded_watershed') np.testing.assert_array_equal(wat_img, im_ref)
def test_plugin_2(): sp_img_ref = imread(data_path('filtering_linearfilter_sigma_3.inr')) sp_img = imread(data_path('filtering_src.inr')) filtered = linear_filtering(sp_img, std_dev=3.0, method='gaussian_smoothing') np.testing.assert_array_equal(filtered, sp_img_ref)
# tmp_im[img2seg <= substract_img] = 0 # img2seg = SpatialImage(tmp_im, voxelsize=vxs, origin=ori) # del tmp_im print "\n# - Automatic seed detection..." from timagetk.plugins import morphology from timagetk.plugins import h_transform from timagetk.plugins import region_labeling from timagetk.plugins import linear_filtering std_dev = 1.0 morpho_radius = 1.0 h_min = 2200 # 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') smooth_img = linear_filtering(img2seg, std_dev=std_dev, method='gaussian_smoothing') ext_img = h_transform(smooth_img, h=h_min, method='h_transform_min') 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))) print "\n - Performing seeded watershed segmentation..." from timagetk.plugins import segmentation std_dev = 1.0 # smooth_img = linear_filtering(img2seg, std_dev=std_dev, method='gaussian_smoothing') seg_im = segmentation(smooth_img, seed_img, method='seeded_watershed') seg_im[seg_im == 0] = back_id # world.add(seg_im, 'seg', colormap='glasbey', alphamap='constant')
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) imsave(base_dir + seg_fname, seg_im) # seg_im = imread(base_dir + seg_fname)
print "\nPerforming 'isometric_resampling'..." img = isometric_resampling(img) # - Performs NUCLEI image subtraction from membrane image: if no_nuc: # -- Reading NUCLEI intensity image: print " --> Reading nuclei image file {}".format( nuc_signal_fname) nuc_im = imread(image_dirname + nuc_path_suffix + nuc_signal_fname) if iso_resampling: print " --> Performing 'isometric_resampling' of nuclei image..." nuc_im = isometric_resampling(nuc_im) # -- Gaussian Smoothing: print " --> Smoothing..." nuc_im = linear_filtering(nuc_im, std_dev=1.0, method='gaussian_smoothing') # -- Remove the NUCLEI signal from the MEMBRANE signal image: print " --> Substracting NUCLEI signal from the MEMBRANE signal image..." zero_mask = np.greater(nuc_im.get_array(), img.get_array()) img = img - nuc_im img[zero_mask] = 0 # world.add(nuc_im, 'nuc_im', colormap='invert_grey') # world.add(img, 'img'+suffix, colormap='invert_grey') print "Done!" del nuc_im, zero_mask # -- Performs intensity rescaling for membrane image: if rescaling == 'AdaptHistEq': print " --> Adaptative Histogram Equalization..." img = z_slice_equalize_adapthist(img)
raise ValueError("Error during relabelling, please check!") else: expert_topomesh = tmp_expert_topomesh # -- Create a seed image from expertised seed positions: print "\n# - Creating seed image from EXPERT seed positions..." xp_seed_pos = expert_topomesh.wisp_property('barycenter', 0) xp_seed_pos = { k: v * microscope_orientation for k, v in xp_seed_pos.items() } # --- Create the seed image: seed_img = seed_image_from_points(size, voxelsize, xp_seed_pos, 2., 0) # --- Add background position: background_threshold = 2000. smooth_img_bck = linear_filtering(img, std_dev=3.0, method='gaussian_smoothing') background_img = (smooth_img_bck < background_threshold).astype(np.uint16) for it in xrange(15): background_img = morphology( background_img, param_str_2='-operation erosion -iterations 10') # ---- Detect small regions defined as background and remove them: connected_background_components, n_components = nd.label(background_img) components_area = nd.sum(np.ones_like(connected_background_components), connected_background_components, index=np.arange(n_components) + 1) largest_component = (np.arange(n_components) + 1)[np.argmax(components_area)] background_img = ( connected_background_components == largest_component).astype(np.uint16) # ---- Finaly add the background and make a SpatialImage:
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, method='gaussian_smoothing') grayscale_imshow([ raw_img.get_z_slice(85), eq_img2.get_z_slice(85), smooth_img.get_z_slice(85) ], img_title=['Original', "CS", 'CS+GS']) ext_img = h_transform(smooth_img, h=h_min, method='h_transform_min') seed_img = region_labeling(ext_img, low_threshold=1, high_threshold=h_min, method='connected_components', param=True) print "Detected {} seeds!".format(len(np.unique(seed_img)) -
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 image_rgb = gray2rgb(img_as_float(int_img)) print image_rgb.shape
except: import sys sys.path.append('/home/marie/SamMaps/scripts/TissueLab/') from equalization import z_slice_contrast_stretch from slice_view import slice_view rescaling = True suffix = "" if rescaling: membrane_img = z_slice_contrast_stretch(membrane_img, pc_max=99) membrane_img = SpatialImage(membrane_img, voxelsize=vxs) suffix += "_contrast_stretch" smooth_img = linear_filtering(membrane_img, std_dev=std_dev, method='gaussian_smoothing') smooth_img = SpatialImage(smooth_img, voxelsize=vxs) x_sh, y_sh, z_sh = smooth_img.shape pc_min = 2 pc_max = 99 title = "Contrast stretched (z-slice): {}pc.-{}pc + gaussian smoothing: std_dev:{}.".format( pc_min, pc_max, std_dev) filename_smooth = filename[: -4] + "_z_contrast_stretch_{}-{}pc, gaussian smoothing_std_dev_{}.png".format( pc_min, pc_max, std_dev) slice_view(smooth_img, x_sh / 2, y_sh / 2, z_sh / 2, title, microscopy_dirname + filename_smooth) # world.add(smooth_img,'membrane_image_adapthist_smooth',colormap='invert_grey')
from timagetk.visu.mplt import grayscale_imshow grayscale_imshow([iso_image, st_img1, st_img2], 100, title=[ "Original", "global_contrast_stretch", "z_slice_equalize_adapthist" ]) seed_detect_img = morphology(st_img2, "erosion", radius=1) seed_detect_img = morphology(seed_detect_img, "coc_alternate_sequential_filter", max_radius=1, iterations=2) seed_detect_img = linear_filtering(seed_detect_img, method="gaussian_smoothing", sigma=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(seed_detect_img, x=mid_x, z=mid_z, plane='z', zone=200) for hmin in [20, 30, 40]: seg_im = auto_seeded_watershed(seed_detect_img, hmin, control='most') # Save the segmented image: seg_fname = base_fname + "-seg_hmin{}{}".format(hmin, ext) imsave(base_dir + seg_fname, seg_im)
from timagetk.util import data_path from timagetk.components import imread, imsave from timagetk.plugins import linear_filtering, morphology from timagetk.plugins import h_transform from timagetk.plugins import region_labeling, segmentation from timagetk.plugins import labels_post_processing except ImportError: raise ImportError('Import Error') out_path = './results/' # to save results # we consider an input image # SpatialImage instance input_img = imread(data_path('input.tif')) # optional denoising block smooth_img = linear_filtering(input_img, std_dev=2.0, method='gaussian_smoothing') asf_img = morphology(smooth_img, max_radius=3, method='co_alternate_sequential_filter') ext_img = h_transform(asf_img, h=150, method='h_transform_min') con_img = region_labeling(ext_img, low_threshold=1, high_threshold=150, method='connected_components') seg_img = segmentation(smooth_img, con_img, control='first', method='seeded_watershed') # optional post processig block pp_img = labels_post_processing(seg_img, radius=1, iterations=1, method='labels_erosion')
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
# new_fold = os.path.join(os.getcwd(),'results') # os.mkdir(new_fold) # we consider an input image # SpatialImage instance input_img = imread(sys.argv[1]) print input_img if input_img.dtype == np.uint8: input_img = input_img.astype(np.uint16) input_img *= 256 # optional denoising block smooth_img = linear_filtering(input_img, std_dev=float(sys.argv[4]), method='gaussian_smoothing') asf_img = morphology(smooth_img, max_radius=1, method='co_alternate_sequential_filter') #opening = morphology(input_img, radius=10, # method='opening') #closing = morphology(input_img, radius=10, # method='dilation') #closing2 = morphology(input_img, radius=1, # method='dilation') """
elif platform.uname()[1] == "calculus": base_dir = '/projects/SamGrowth/microscopy/20180616_global_della_Ler_LD' 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,