def read_image(im_fname, channel_names=None, pattern='..CZXY.'): """ Read CZI, LSM, TIF and INR images based on the 'im_fname' extension. Parameters ---------- im_fname : str filename of the image to read. channel_names : list(str), optional list of channel names to use if im_fname is a multi-channel image pattern : str, optional CZI data ordering pattern, often '..CZXY.' or '.C.ZXY.' Returns ------- im : SpatialImage|dict(SpatialImage) SpatialImage or dictionary of SpatialImages if a multi-channel images """ if im_fname.endswith(".inr") or im_fname.endswith(".inr.gz"): im = imread(im_fname) elif im_fname.endswith(".tif"): im = imread(im_fname) elif im_fname.endswith(".lsm"): im = read_lsm(im_fname) if isinstance(im, dict): im = { k: SpatialImage(ch, voxelsize=ch.voxelsize) for k, ch in im.items() } if channel_names is not None: im = replace_channel_names(im, channel_names) else: im = SpatialImage(im, voxelsize=im.voxelsize) elif im_fname.endswith(".czi"): im = read_czi(im_fname, channel_names, pattern=pattern) # try: # im2 = read_czi(im_fname) # assert isinstance(im2, dict) # except: # del im2 # else: # im = im2 for k, ch in im.items(): if not isinstance(ch, SpatialImage): im[k] = SpatialImage(ch, voxelsize=ch.voxelsize) else: raise TypeError("Unknown reader for file '{}'".format(im_fname)) return im
def add_channel_regitration(czi_base_fname, nomenclature_file, ch_name, trsf_type, temp_reg, image_dirname, colormap='invert_grey'): """ Add the registered image to tissuelab world. """ for n, (t_ref, t_float) in enumerate(temp_reg): # -- Get the reference CZI file names: ref_czi_fname = czi_base_fname.format(t_ref) # -- Get the reference INR file names: ref_path_suffix, ref_img_fname = get_nomenclature_channel_fname( ref_czi_fname, nomenclature_file, ch_name) if n == 0: print "Reading last time-point (t{}) image filename: {}".format( t_ref, ref_img_fname) ref_im = imread(image_dirname + ref_path_suffix + ref_img_fname) if ch_name.find('raw') != -1: ref_im = z_slice_equalize_adapthist(ref_im) world.add(ref_im, ref_img_fname, colormap='Reds') # -- Get the float CZI file names: float_czi_fname = czi_base_fname.format(t_float) # -- Get the float INR file names: float_path_suffix, float_img_fname = get_nomenclature_channel_fname( float_czi_fname, nomenclature_file, ch_name) # --- Get RESULT rigid transformation image filename: res_path_suffix = float_path_suffix + trsf_type + "_registrations/" res_img_fname = get_res_img_fname(float_img_fname, t_ref, t_float, trsf_type) # -- Read RESULT image file: res_im = imread(image_dirname + res_path_suffix + res_img_fname) print "Reading result floating (t{}) image filename: {}".format( t_float, res_img_fname) world.add(res_im, res_img_fname, colormap='Greens') return "Done."
def main(): # - Argument parsing: parser = argparse.ArgumentParser(description="Convert inr images to tif format.") # -- MANDATORY arguments: parser.add_argument('inr', type=list, nargs='+', help='Image or list of images to convert.') input_args = parser.parse_args() # Check "images" (list) to convert to *.inr: img_list = [''.join(fname) for fname in input_args.inr] print img_list try: assert img_list != [] except: raise TypeError("Could not understand the list of provided filenames.") # Performs czi to inr convertion: for input_img in img_list: tif_fname = splitext_zip(input_img)[0] + '.tif' imsave(tif_fname, imread(input_img))
# Get unregistered image filename: path_suffix, PI_signal_fname = get_nomenclature_channel_fname( czi_fname, nomenclature_file, membrane_ch_name) path_suffix, PIN_signal_fname = get_nomenclature_channel_fname( czi_fname, nomenclature_file, 'PIN1') path_suffix, seg_img_fname = get_nomenclature_segmentation_name( czi_fname, nomenclature_file, membrane_ch_name + "_raw") # - To create a mask, edit a MaxIntensityProj with an image editor (GIMP) by adding 'black' (0 value): # mask = image_dirname+'PIN1-GFP-CLV3-CH-MS-E1-LD-SAM4-MIP_PI-mask.png' mask = '' print "\n\n# - Reading PIN1 intensity image file {}...".format( PIN_signal_fname) PIN_signal_im = imread(image_dirname + path_suffix + PIN_signal_fname) # PIN_signal_im = isometric_resampling(PIN_signal_im) # world.add(PIN_signal_im, 'PIN1 intensity image', colormap='viridis', voxelsize=PIN_signal_im.voxelsize) print "\n\n# - Reading PI intensity image file {}...".format(PI_signal_fname) PI_signal_im = imread(image_dirname + path_suffix + PI_signal_fname) # PI_signal_im = isometric_resampling(PI_signal_im) # world.add(PI_signal_im, 'PI intensity image', colormap='invert_grey', voxelsize=PI_signal_im.voxelsize) print "\n\n# - Reading segmented image file {}...".format(seg_img_fname) seg_im = imread(image_dirname + path_suffix + seg_img_fname) seg_im[seg_im == 0] = back_id ############################################################################### # -- PIN1/PI signal & PIN1 polarity quatification: ###############################################################################
# -- Output format: out_fmt = args.out_fmt.split('.')[-1] try: assert out_fmt in SUPPORTED_FMT except AssertionError: raise TypeError("Unkown output file format '{}', supported formats are: '{}'.".format(out_fmt, SUPPORTED_FMT)) # -- Force overwrite existing file: force = args.force if force: print "WARNING: any existing image will be overwritten!" else: print "Existing images will be kept!" # - Loading the LSM to convert: lsm_im = imread(lsm_fname) # -- Make the base filename to output (channel name & exrtension added later!) output_fname = args.output_fname if output_fname == "": output_fname = splitext(lsm_fname)[0] # - Save to given format: img_fname = output_fname + '.{}'.format(out_fmt) if exists(img_fname) and not force: print "Found existing file: {}".format(img_fname) print "Use '--force' argument to overwrite it!" else: print "Saving to '{}' format under: '{}'".format(out_fmt.upper() ,img_fname) imsave(img_fname, lsm_im)
from timagetk.io import imread, imsave from timagetk.plugins.registration import z_stack_registration, apply_z_stack_trsf # root_dir = '/projects/SamMaps/SuperResolution/LSM Airyscan/' root_dir = '/data/Meristems/Carlos/SuperResolution/' base_fname = 'SAM1-gfp-pi-stack-LSM800-Airyscan Processing-standard_{}.tif' ref_channel = 'PI_SR' float_channels = ['PIN_SR', 'PI_conf', 'PIN_conf'] image = imread(root_dir + base_fname.format(ref_channel)) reg_method = 'rigid' reg_stack, z_stack_trsf = z_stack_registration(image, method=reg_method, get_trsf=True) # - Have a look at the z-stack registration results on PI channel: from timagetk.visu.mplt import grayscale_imshow mid_y = int(image.get_y_dim()/2.) grayscale_imshow([image.get_y_slice(mid_y), reg_stack.get_y_slice(mid_y)], title="Z-stack {} registration - y-slice {}/{}".format(reg_method, mid_y, image.get_y_dim()), subplot_titles=['Original', 'Registered'], range=[0, 10000]) grayscale_imshow([image, reg_stack], title="Z-stack {} registration - Contour projection".format(reg_method), subplot_titles=['Original', 'Registered'], range=[0, 10000]) from timagetk.visu.mplt import stack_browser stack_browser(reg_stack, title="{} registered z-stack".format(reg_method)) from timagetk.visu.mplt import stack_browser_RGBA stack_browser_RGBA([image, reg_stack], channel_names=['Original', 'Registered'], colors=['red', 'green'], title="Z-stack {} registration".format(reg_method)) imsave(root_dir + base_fname.format(ref_channel+"_z-stack_reg"), reg_stack) # - Apply this registration to the other channels: for float_channel in float_channels: image = imread(root_dir + base_fname.format(float_channel))
from timagetk.plugins import linear_filtering from timagetk.algorithms import isometric_resampling import sys sys.path.append('/home/marie/SamMaps/scripts/TissueLab/') from equalization import z_slice_contrast_stretch from equalization import x_slice_contrast_stretch from equalization import y_slice_contrast_stretch from equalization import z_slice_equalize_adapthist from slice_view import slice_view from slice_view import slice_n_hist dirname = '/home/marie/Carlos/qDII-CLV3-PIN1-PI-E35-LD/SAM4/' fname = '/qDII-CLV3-PIN1-PI-E35-LD-SAM4-T0_CH2_iso.inr' img = imread(dirname + fname) x_sh, y_sh, z_sh = img.shape z_slice = 107 # Display slice and histograms: slice_n_hist(img[:,:,z_slice], 'Original image', 'z-slice {}/{}'.format(z_slice, z_sh)) # Display orthogonal view of ORIGINAL image: slice_view(img, x_sh/2, y_sh/2, z_sh/2, 'original_image', dirname + fname[:-4] + ".png") # Display and save orthogonal view of EQUALIZE ADAPTHIST image for various clip_limit: for clip_limit in [0.005,0.007,0.01,0.02,0.05,0.1]: im_eq = z_slice_equalize_adapthist(img,clip_limit=float(clip_limit)) x_sh, y_sh, z_sh = im_eq.shape
microscopy_dirname = dirname + "/Carlos/qDII-CLV3-PIN1-PI-E35-LD/SAM4/" filename = 'qDII-CLV3-PIN1-PI-E35-LD-SAM4-T0.czi' nomenclature_file = dirname + "/SamMaps/nomenclature.csv" nomenclature_data = pd.read_csv(nomenclature_file, sep=';')[:-1] nomenclature_names = dict( zip(nomenclature_data['Name'], nomenclature_data['Nomenclature Name'])) reference_name = 'TagBFP' membrane_name = 'PI' microscope_orientation = -1 membrane_image_filename = image_dirname + "/" + nomenclature_names[ filename] + "/" + nomenclature_names[ filename] + "_" + membrane_name + ".inr.gz" membrane_img = imread(membrane_image_filename) mask_filename = image_dirname + "/" + nomenclature_names[ filename] + "/" + nomenclature_names[filename] + "_mask.inr.gz" mask_img = imread(mask_filename) membrane_img[mask_img == 0] = 0 # world.add(membrane_img,'membrane_image',colormap='invert_grey') #world['membrane_image']['intensity_range'] = (5000,30000) topomesh_file = image_dirname + "/" + nomenclature_names[ filename] + "/" + nomenclature_names[ filename] + "_nuclei_detection_topomesh_corrected.ply" topomesh = read_ply_property_topomesh(topomesh_file) positions = topomesh.wisp_property('barycenter', 0) positions = array_dict(microscope_orientation * positions.values(),
from timagetk.io import imread from timagetk.io import imsave from timagetk.plugins import morphology from timagetk.plugins import h_transform from timagetk.plugins import region_labeling from timagetk.plugins import linear_filtering from timagetk.plugins import segmentation 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)
trsf_type) res_path = float_img_path + '{}_registrations/'.format(trsf_type) # - Get sequence registration result trsf filename and write trsf: # res_trsf_list.append(res_path + get_res_trsf_fname(float_img_fname, t_ref, t_float, trsf_type)) seq_res_trsf_list.append(res_path + get_res_trsf_fname( float_img_fname, t_ref, t_float, "sequence_" + trsf_type)) print "" for f in seq_res_trsf_list: print "Existing tranformation file {}: {}\n".format(f, exists(f)) list_img = [] print "\n# - Loading list of images for which to apply registration process:" for n, img_fname in enumerate(list_img_fname): print " - Time-point {}, reading image {}...".format(n, img_fname) im = imread(img_fname) if ref_ch_name.find('raw') != -1: im = z_slice_contrast_stretch(im) else: pass list_img.append(im) list_comp_trsf, list_res_img = [], [] # if not np.all([exists(f) for f in res_trsf_list]) or force: if not np.all([exists(f) for f in seq_res_trsf_list]) or force: if not_sequence: list_comp_trsf, list_res_img = registration( list_img[0], list_img[1], method='{}_registration'.format(trsf_type)) list_comp_trsf = [list_comp_trsf]
# filenames = ['Lti6b_xy0.156_z0.8_CH0_iso.inr', # 'Lti6b_xy0.156_z0.32_CH0_iso.inr', # 'Lti6b_xy0.156_z0.156_CH0_iso.inr', # 'Lti6b_xy0.156_z0.32_pinH0.34_CH0_iso.inr', # 'Lti6b_xy0.156_z0.80_pinH0.34_CH0_iso.inr'] microscope_orientation = -1 # reference_name = "tdT" reference_name = "PI" image_filename = image_dirname + "/" + filename + "/" + filename + "_" + reference_name + ".inr.gz" # Original image #------------------------------ img = imread(image_filename) size = np.array(img.shape) voxelsize = np.array(img.voxelsize) # Mask #------------------------------ ## mask image obtein by maximum intensity projection : # mask_filename = image_dirname+"/"+filename+"/"+filename+"_projection_mask.inr.gz" ## 3D mask image obtein by piling a mask for each slice : mask_filename = image_dirname + "/" + filename + "/" + filename + "_mask.inr.gz" if exists(mask_filename): mask_img = imread(mask_filename) else: mask_img = np.ones_like(img) img[mask_img == 0] = 0
extra_channels = list(set(channel_names) - set([membrane_ch_name])) # By default do not recompute deformation when an associated file exist: force = False from timagetk.plugins import sequence_registration print "\n# - Building list of images for which to apply registration process:" list_img_fname, list_img = [], [] for n, t in enumerate(time_steps): # -- Get the INR file names: path_suffix, img_fname = get_nomenclature_channel_fname( czi_base_fname.format(t), nomenclature_file, membrane_ch_name) print " - Time-point {}, reading image {}...".format(n, img_fname) img_fname = image_dirname + path_suffix + img_fname list_img_fname.append(img_fname) im = imread(img_fname) if membrane_ch_name.find('raw') != -1: im = z_slice_equalize_adapthist(im) else: pass list_img.append(im) print "\n# - Computing sequence {} registration:".format(trsf_type.upper()) list_comp_tsrf, list_res_img = sequence_registration( list_img, method='sequence_{}_registration'.format(trsf_type)) force = True ref_im = list_img[-1] # reference image is the last time-point time2index = {t: n for n, t in enumerate(time_steps)} composed_trsf = zip(list_comp_tsrf, time_steps[:-1]) for trsf, t in composed_trsf: # 't' here refer to 't_float'
# # # Extract topological elements coordinates: # elem = cell_topological_elements_extraction(im) # # Get the cell-vertex coordinates between labels 1, 2, 3 and 4 # elem[0] # # Get the wall-edge voxel coordinates between labels 1, 2 and 3: # elem[1][(1, 2, 3)] # # Get the wall voxel coordinates between labels 1 and 4: # elem[2][(1, 4)] # from openalea.cellcomplex.property_topomesh.property_topomesh_creation import vertex_topomesh # topomesh = vertex_topomesh(elem[0]) # world.add(topomesh, 'detected_cell_vertex', colormap='Reds') im_fname = '/data/Meristems/Carlos/PIN_maps/nuclei_images/qDII-PIN1-CLV3-PI-LD_E37_171113_sam07_t14/qDII-PIN1-CLV3-PI-LD_E37_171113_sam07_t14_PI_segmented.inr.gz' im = imread(im_fname) elem = cell_topological_elements_extraction(im[300:-300, 300:-300, :]) wall_coords = elem[2] wall_edge_coords = elem[1] wall_vertex_coords = elem[0] import vplants.tissue_analysis.spatial_image_analysis reload(vplants.tissue_analysis.spatial_image_analysis) from vplants.tissue_analysis.spatial_image_analysis import find_pointset_median from vplants.tissue_analysis.spatial_image_analysis import find_geometric_median wmv = find_pointset_median(wall_coords, labels2exclude=None, return_id=False) wemv = find_pointset_median(wall_edge_coords, labels2exclude=None, return_id=False) wvmv = find_pointset_median(wall_vertex_coords, labels2exclude=None, return_id=False)
tp2ts = dict(zip(time_points, time_steps)) ts2tp = dict(zip(time_steps, time_points)) # - Registered intensity image, segmented images & transformation file path: reg_path = dir_path + 'registered_sequence/' trsf_name = "t{}-t{}_{}.trsf" # t0, t1, trsf_type try: mkdir(reg_path) except OSError: pass # - Load images: list_image = [] for tp in time_points: fname = int_fname.format(tp2ts[tp], '', ext) list_image.append(imread(int_path + fname)) print(list_image[-1].filename) print(list_image[-1].shape) print(list_image[-1].voxelsize) ref_tp = time_points[-1] t_ref = time_steps[-1] vxs = 0.2415 # - Resample the last time-point (reference) to the registered path: # -- ISOMETRIC resampling of INTENSITY image: list_image[ref_tp] = isometric_resampling(list_image[ref_tp], method=vxs, option='gray') # Save rigid sequence registered intensity images: fname_res_int = reg_path + int_fname.format(t_ref, '', ext) print("Saving:", fname_res_int) imsave(fname_res_int, list_image[ref_tp])
from timagetk.visu.mplt import grayscale_imshow, stack_browser, channels_stack_browser from timagetk.algorithms.resample import isometric_resampling from timagetk.plugins.projection import projection root_dir = '/projects/lsfm/multi_view/20190430_M_lti6b-gfp' filenames = [ '20190430_multiangle_top.tif', '20190430_multiangle_0.tif', '20190430_multiangle_45.tif', '20190430_multiangle_90.tif', '20190430_multiangle_135.tif', '20190430_multiangle_180.tif', '20190430_multiangle_-45.tif', '20190430_multiangle_-90.tif', '20190430_multiangle_-135.tif' ] proj_list = [] for fname in filenames: img = imread(root_dir + "/" + fname) print "{}: shape={}, voxelsize={}".format(img.filename, img.shape, img.voxelsize) proj_list.append(projection(img, method='contour')) grayscale_imshow(proj_list, range='auto', title='20190430_M_lti6b-gfp', subplot_titles=filenames, figname=root_dir + "/" + "contour_projections.png") # filenames = ['20190430_multiangle_top.tif', '20190430_multiangle_45.tif'] # list_img = [imread(root_dir+"/"+im) for im in filenames] # res_trsf, res_imgs = fusion_on_first(list_img, registration_method='rigid')
std_dev_range = np.concatenate((np.array([0]), np.arange(1.0, 2.0, 0.2))) rescale_type = ['Original', 'AdaptHistEq', 'ContrastStretch'] for rescaling in rescale_type: for iso_resampling in [False, True]: for std_dev in std_dev_range: # - build a string collecting list of algorithm applied to the nuclei image suffix = '-' + rescaling + ('-iso' if iso_resampling else '') + ('-gauss_smooth_{}'.format(std_dev) if std_dev != 0 else '') print "\n\nPerforming detection case: {}".format(suffix) # - Get the name of the topomesh file: topomesh_file = image_dirname + nuc_path_suffix + nuc_path_suffix[:-1] + "{}_nuclei_detection.ply".format(suffix) if exists(topomesh_file) and not force: print "Found topomesh file:\n{}".format(topomesh_file) detected_topomesh = read_ply_property_topomesh(topomesh_file) else: print "No topomesh file detected, running detection script..." img = imread(image_dirname + nuc_path_suffix + nuc_signal_fname) if rescaling == 'AdaptHistEq': print "\nPerforming 'z_slice_equalize_adapthist'..." img = z_slice_equalize_adapthist(img) # world.add(img, "reference_image"+suffix, colormap="invert_grey", voxelsize=microscope_orientation*voxelsize) if rescaling == 'ContrastStretch': print "\nPerforming 'z_slice_contrast_stretch'..." img = z_slice_contrast_stretch(img) # world.add(img, "reference_image"+suffix, colormap="invert_grey", voxelsize=microscope_orientation*voxelsize) # - Performs masked subtraction of signal: try: img[mask_img == 0] = 0 except: pass else: print "Applied mask to nuclei signal...",
from timagetk.components import SpatialImage from timagetk.io import imread from timagetk.io import imsave from timagetk.plugins import registration from timagetk.plugins import morphology raw_float_img = imread("/data/GabriellaMosca/EM_C_140/EM_C_140- C=0.tif") raw_ref_img = imread("/data/GabriellaMosca/EM_C_214/EM_C_214 C=0.tif") mask_seg_float_img = imread( "/data/GabriellaMosca/EM_C_140/C3-EM_C_C2_relabeledCropped.tif") mask_seg_float_img = mask_seg_float_img.revert_axis('y') mask_seg_float_img = mask_seg_float_img.astype('uint8') imsave("/data/GabriellaMosca/EM_C_140/EM_C_140-segmented.tif", mask_seg_float_img) mask_seg_ref_img = imread( "/data/GabriellaMosca/EM_C_214/EM_C_214_ C=1_relabeledAndCropped.tif") mask_seg_ref_img = mask_seg_ref_img.revert_axis('y') mask_seg_ref_img = mask_seg_ref_img.astype('uint8') imsave("/data/GabriellaMosca/EM_C_214/EM_C_214-segmented.tif", mask_seg_ref_img) ################################################################################ # - Apply morphological filters: from scipy import ndimage POSS_METHODS = ["erosion", "dilation", "opening", "closing"]
import numpy as np 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
from timagetk.algorithms.resample import isometric_resampling from timagetk.plugins import linear_filtering 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)
from timagetk.plugins import auto_seeded_watershed from timagetk.visu.mplt import profile_hmin from os.path import join import sys, platform if platform.uname()[1] == "RDP-M7520-JL": base_dir = '/data/Meristems/Bihai/20180616_3-global_della_Ler_LD/' 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' base_fname, ext = splitext(fname) image = imread(base_dir + fname) image.voxelsize iso_image = isometric_resampling(image, method='min', option='cspline') iso_image.shape iso_image = z_slice_equalize_adapthist(iso_image) # iso_image = z_slice_contrast_stretch(iso_image, pc_min=1.5) iso_image = linear_filtering(iso_image, method="gaussian_smoothing", sigma=0.25, real=True) xsh, ysh, zsh = iso_image.shape mid_x, mid_y, mid_z = int(xsh / 2.), int(ysh / 2.), int(zsh / 2.)
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') from timagetk.io import imsave imsave(seg_img_fname, seg_im) else: from timagetk.io import imread seg_im = imread(seg_img_fname) ############################################################################### # -- MAYAVI VISU: ############################################################################### # from mayavi import mlab # from os.path import splitext # import numpy as np # from timagetk.io import imread # from vplants.tissue_analysis.spatial_image_analysis import SpatialImageAnalysis # dirname = "/data/Meristems/Carlos/PIN_maps/" # image_dirname = dirname + "nuclei_images/" # path_suffix = "test_offset/" # # im_tif = "qDII-CLV3-PIN1-PI-E37-LD-SAM7-T5-P2.tif" # im_tif = "qDII-CLV3-PIN1-PI-E37-LD-SAM7-T14-P2.tif" #
# world.add(L1_expert_topomesh,"L1_expert_seeds") # world["L1_expert_seeds"]["property_name_0"] = 'layer' # world["L1_expert_seeds_vertices"]["polydata_colormap"] = load_colormaps()['Greens'] # EVALUATION #--------------------------------------------------- evaluations = {} L1_evaluations = {} ## Parameters std_dev = 2.0 morpho_radius = 3 h_min = 230 # - EXPERT evaluation: topomesh_file = image_dirname + xp_filename[:-4] + "_seed_wat_EXPERT_detection_topomesh.ply" img = imread(image_dirname + xp_filename) img = isometric_resampling(img) # world.add(img,"iso_ref_image"+suffix, colormap="invert_grey", voxelsize=microscope_orientation*voxelsize) size = np.array(img.shape) voxelsize = np.array(img.voxelsize) if exists(topomesh_file): detected_topomesh = read_ply_property_topomesh(topomesh_file) else: print "Shape: ", img.shape, "; Size: ", img.voxelsize # -- Change following values, as required by watershed algorithm: # - '0': watershed will fill these with other label # - '1': background value (outside the biological object) vtx = list(expert_topomesh.wisps(0)) if 0 in vtx or 1 in vtx: # --- Initialise relabelling dictionary:
'Lti6b_xy0.156_z0.8_CH0_iso', 'Lti6b_xy0.156_z0.32_CH0_iso', 'Lti6b_xy0.156_z0.156_CH0_iso', 'Lti6b_xy0.156_z0.32_pinH0.34_CH0_iso', 'Lti6b_xy0.156_z0.80_pinH0.34_CH0_iso', 'Lti6b_xy0.313_z0.8_zoom0.5_CH0_iso' ] #reference_name = "PI" reference_name = "Lti6b" microscope_orientation = +1 for filename in filenames: image_filename = image_dirname + filename + ".inr" img = imread(image_filename) size = np.array(img.shape) voxelsize = np.array(img.voxelsize) x_sh, y_sh, z_sh = img.shape # Display orthogonal view of ORIGINAL image: slice_view(img, x_sh / 2, y_sh / 2, z_sh / 2, filename[:-8] + '\n original_image', image_filename[:-4] + ".png") world.add(img, "reference_image", colormap="invert_grey", voxelsize=microscope_orientation * voxelsize) # parameters pc_min, pc_max = 2, 99
# -4- Define CZI channel names, the microscope orientation, nuclei and membrane channel names and extra channels that should also be registered: time_steps = [0, 5, 10, 14] channel_names = ['DIIV', 'PIN1', 'PI', 'TagBFP', 'CLV3'] microscope_orientation = -1 # inverted microscope! ref_ch_name = 'PI' nuc_ch_name = "TagBFP" nuc_path_suffix, nuc_signal_fname = get_nomenclature_channel_fname( czi_fname, nomenclature_file, nuc_ch_name) memb_path_suffix, memb_signal_fname = get_nomenclature_channel_fname( czi_fname, nomenclature_file, ref_ch_name) # Original MEMBRANE image #------------------------------ img = imread(image_dirname + memb_path_suffix + memb_signal_fname) size = np.array(img.shape) vxs = np.array(img.voxelsize) ori = np.array(img.voxelsize) # Mask #------------------------------ ## mask image obtein by maximum intensity projection : # mask_filename = image_dirname+"/"+filename+"/"+filename+"_projection_mask.inr.gz" ## 3D mask image obtein by piling a mask for each slice : mask_filename = image_dirname + memb_path_suffix + memb_path_suffix[:-1] + "_mask.inr.gz" if os.path.exists(mask_filename) and 'raw' in ref_ch_name: print "Found mask image: '{}'".format(mask_filename) mask_img = imread(mask_filename) img[mask_img == 0] = 0
for tp, t in enumerate(time_steps): raw_czi_fname = czi_base_fname.format(t) print "\n\n# - Entering segmentation process for {}".format(raw_czi_fname) start = time.time() # - Defines segmented file name and path: seg_path_suffix, seg_img_fname = get_nomenclature_segmentation_name(raw_czi_fname, nom_file, ref_ch_name) if os.path.exists(image_dirname + seg_path_suffix + seg_img_fname) and not force: print "A segmentation file '{}' already exists, aborting now.".format(seg_img_fname) sys.exit(0) # - Get the image to segment: # -- Get the file name and path of the image to segment: path_suffix, img2seg_fname = get_nomenclature_channel_fname(raw_czi_fname, nom_file, ref_ch_name) print "\n - Loading image to segment: {}".format(img2seg_fname) img2seg = imread(image_dirname + path_suffix + img2seg_fname) vxs = np.array(img2seg.voxelsize) ori = np.array(img2seg.origin) # -- Get the file name and path of the channel to substract to the image to segment: # used to clear-out the cells for better segmentation if clearing_ch_name: path_suffix, substract_img_fname = get_nomenclature_channel_fname(raw_czi_fname, nom_file, clearing_ch_name) print "\n - Loading image to substract: {}".format(substract_img_fname) substract_img = imread(image_dirname + path_suffix + substract_img_fname) # substract the 'CLV3' signal from the 'PI' since it might have leaked: print "\n - Performing images substraction..." tmp_im = img2seg - substract_img tmp_im[img2seg <= substract_img] = 0 img2seg = SpatialImage(tmp_im, voxelsize=vxs, origin=ori) del tmp_im # -- Display the image to segment:
rig_seg_img_fname = get_res_img_fname(seg_img_fname, t_ref, t_float, 'iso-rigid') res_path = image_dirname + rig_float_path_suffix try: assert exists(res_path + rig_seg_img_fname) except: # - Get the result image file name & path (output path), and create it if necessary: if not exists(res_path): mkdir(res_path) print "\n# - RIGID registration for t{}/t{}:".format( time2index[t_float], time2index[t_ref]) py_hl = 3 # defines highest level of the blockmatching-pyramid py_ll = 1 # defines lowest level of the blockmatching-pyramid print ' - t_{}h floating fname: {}'.format(t_float, float_img_fname) im_float = imread(image_dirname + float_path_suffix + float_img_fname) if float_img_fname.find('iso') == -1: # if not isometric, resample! im_float = isometric_resampling(im_float) print ' - t_{}h reference fname: {}'.format(t_ref, ref_img_fname) im_ref = imread(image_dirname + ref_path_suffix + ref_img_fname) if ref_img_fname.find('iso') == -1: # if not isometric, resample! im_ref = isometric_resampling(im_ref) print "" res_trsf, res_im = registration(im_float, im_ref, method='rigid_registration', pyramid_highest_level=py_hl, pyramid_lowest_level=py_ll) print "" # - Save result image and tranformation: print "Writing image file: {}".format(rig_float_img_fname)
from timagetk.components import SpatialImage from timagetk.wrapping import BalTrsf from timagetk.io import imread from timagetk.io import imsave from timagetk.plugins import registration from timagetk.plugins import morphology raw_ref_img = imread("/data/GabriellaMosca/EM_C_140/EM_C_140- C=0.tif") raw_float_img = imread("/data/GabriellaMosca/EM_C_214/EM_C_214 C=0.tif") ref_img = imread("/data/GabriellaMosca/EM_C_140/EM_C_140-masked.tif") float_img = imread("/data/GabriellaMosca/EM_C_214/EM_C_214-masked.tif") init_trsf = BalTrsf() init_trsf.read('/data/GabriellaMosca/T140_214.trsf') trsf_def, img_def = registration(float_img, ref_img, method='deformable', init_trsf=init_trsf) imsave("/data/GabriellaMosca/EM_C_214/EM_C_214-masked_deformable.tif", img_def) from timagetk.visu.mplt import grayscale_imshow img2plot = [float_img, ref_img, img_rig, ref_img] img_titles = ["t0", "t1", "Registered t0 on t1", "t1"] grayscale_imshow(img2plot, "Effect of rigid registration", img_titles,
print "\n# - Building list of image filenames for which to apply registration process:" list_img_fname = [] for ind, t in enumerate(time_steps): # -- Get the INR file names: path_suffix, img_fname = get_nomenclature_channel_fname(czi_base_fname.format(t), nom_file, ref_ch_name) print " - Time-point {}, adding image {}...".format(ind, img_fname) img_fname = image_dirname + path_suffix + img_fname list_img_fname.append(img_fname) list_img = [] print "\n# - Loading list of images for which to apply registration process:" for ind, img_fname in enumerate(list_img_fname): print " - Time-point {}, reading image {}...".format(ind, img_fname) im = imread(img_fname) if ref_ch_name.find('raw') != -1: im = z_slice_contrast_stretch(im) else: pass list_img.append(im) # - Resample to isometric voxelsize to be able to apply it to isometric segmented image: print "\nResample to isometric voxelsize to be able to apply it to isometric segmented image:" list_iso_img = [isometric_resampling(im) for im in list_img] from timagetk.algorithms import blockmatching trsf_type = 'iso-deformable' list_res_trsf, list_res_img = [], []
from os.path import join import sys, platform if platform.uname()[1] == "RDP-M7520-JL": base_dir = '/data/Meristems/Bihai/20180616_3-global_della_Ler_LD/' 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)