Beispiel #1
0
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))
Beispiel #2
0
else:
    print "Existing images will be kept!"

# - Loading the CZI to convert:
czi_im = read_image(czi_fname, channel_names, pattern)
nb_ch = len(czi_im)

# -- Restricted list of channel to convert:
out_channels = args.out_channels
if out_channels == "":
    print "All {} channels will be extracted".format(nb_ch)
    out_channels = channel_names
else:
    print "Only the following channels will be extracted: '{}'".format(out_channels)

# -- Make the base filename to output (channel name & exrtension added later!)
output_fname =  args.output_fname
if output_fname == "":
    output_fname = splitext(czi_fname)[0]
print "Base filename used to export channels is: '{}'".format(output_fname)

# - Save required channels:
for ch in out_channels:
    img_fname = output_fname + '_{}.{}'.format(ch, out_fmt)
    if exists(img_fname) and not force:
        print "Found existing file: {}".format(img_fname)
    else:
        im = czi_im[ch]
        print "\n - Saving channel '{}' under: '{}'".format(ch ,img_fname)
        imsave(img_fname, im)
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)

    # blend = label_blending(seg_im, iso_image)
    # from timagetk.visu.mplt import rgb_stack_browser
    # rgb_stack_browser(blend)

    from timagetk.visu.mplt import gif_slice_blending
    gif_fname = base_fname + "-seg_hmin{}{}".format(selected_hmin, '.gif')
    gif_slice_blending(seg_im,
                       iso_image,
                       base_dir + gif_fname,
                       duration=5.,
                       out_shape=[256, 256])
Beispiel #4
0
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])

    out_fname += '.' + ext
    print "\nSaving file: '{}'".format(out_fname)
    # - Save the cropped-image:
    imsave(out_fname, im)
Beispiel #5
0
            # print '  - {} t_{}h/t_{}h composed-trsf as initialisation'.format(trsf_type, t, t_ref)
            print ""
            # res_trsf, res_im = registration(float_im, ref_im, method='{}_registration'.format(trsf_type), init_trsf=trsf, pyramid_highest_level=py_hl, pyramid_lowest_level=py_ll)
            res_trsf, res_im = registration(
                list_res_img[time2index[t]],
                ref_im,
                method='{}_registration'.format(trsf_type),
                pyramid_highest_level=py_hl,
                pyramid_lowest_level=py_ll)
            # res_trsf, res_im = registration(float_im, ref_im, method='{}_registration'.format(trsf_type), left_trsf=trsf, pyramid_highest_level=py_hl, pyramid_lowest_level=py_ll)
            res_trsf = compose_trsf([trsf, res_trsf], template_img=ref_im)
            print ""

        # - Save result image and tranformation:
        print "Writing image file: {}".format(res_img_fname)
        imsave(res_path + res_img_fname,
               apply_trsf(imread(float_img_path + float_img_fname), res_trsf))
        print "Writing trsf file: {}".format(res_trsf_fname)
        save_trsf(res_trsf, res_path + res_trsf_fname)
    else:
        print "Existing image file: {}".format(res_img_fname)
        print "Loading existing {} transformation file: {}".format(
            trsf_type.upper(), res_trsf_fname)
        res_trsf = read_trsf(res_path + res_trsf_fname)

    # -- Apply estimated transformation to other channels of the floating CZI:
    if extra_channels:
        print "\nApplying estimated {} transformation on '{}' to other channels: {}".format(
            trsf_type.upper(), ref_ch_name, ', '.join(extra_channels))
        for x_ch_name in extra_channels:
            # --- Get the extra channel filenames:
            x_ch_path_suffix, x_ch_fname = get_nomenclature_channel_fname(
Beispiel #6
0
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"]
DEFAULT_METHOD = 0
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))
    reg_image = apply_z_stack_trsf(image, z_stack_trsf)
    imsave(root_dir + base_fname.format(float_channel+"_z-stack_reg"), reg_image)
Beispiel #8
0
     print "--> Reading {} transformation file: '{}'".format(trsf_type.upper(), out_trsf_fname)
     out_trsf = read_trsf(out_folder + out_trsf_fname)
 else:
     print "\nFound existing tranformation t{}->t{}!".format(i_float, i_ref)
     print "--> Nothing left to do here..."
 if write_cons_img:
     print "\n{} registration of the float intensity image:".format(trsf_type.upper())
     # - Defines the registered image filename (output):
     out_img_fname = get_res_img_fname(float_img_fname, t_ref, t_float, trsf_type)
     if not exists(join(out_folder, out_img_fname)) or force:
         # -- Apply the transformation to the intensity image:
         print "--> Apply tranformation to the float intensity image..."
         out_img = apply_trsf(float_img, trsf=out_trsf, template_img=ref_img)
         # -- Save the registered image:
         print "--> Saving t{} registered intensity image: '{}'".format(i_float, out_img_fname)
         imsave(out_folder + out_img_fname, out_img)
         del out_img
     else:
         print "--> Found existing t{} registered intensity image: '{}'".format(i_float, out_img_fname)
 if extra_im is not None:
     print "\n{} registration of the EXTRA intensity image:".format(trsf_type.upper())
     # -- Defines the registered extra intensity image filename (output):
     ximg_path, ximg_fname = split(indexed_ximg_fnames[i_float])
     out_ximg_fname = get_res_img_fname(ximg_fname, t_ref, t_float, trsf_type)
     if not exists(join(out_folder, out_ximg_fname)) or force:
         # - Also apply transformation to extra image:
         # -- Read this extra intensity image file:
         print "--> Reading t{} EXTRA intensity image file: '{}'".format(i_float, out_ximg_fname)
         ximg = read_image(join(ximg_path, ximg_fname))
         # -- Apply the transformation to the extra intensity image:
         print "--> Apply tranformation to the EXTRA intensity image..."
# Add the "background seed":
background_threshold = 2000.
smooth_img_bck = linearfilter(membrane_img,
                              param_str_2='-x 0 -y 0 -z 0 -sigma 3.0')
background_img = (smooth_img_bck < background_threshold).astype(np.uint16)
for it in xrange(10):
    background_img = morphology(
        background_img, param_str_2='-operation erosion -iterations 10')
seed_img += background_img
seed_img = SpatialImage(seed_img, voxelsize=membrane_img.voxelsize)
#world.add(seed_img,'seed_image',colormap='glasbey',alphamap='constant',bg_id=0)
segmented_filename = image_dirname + "/" + nomenclature_names[
    filename] + "/" + nomenclature_names[
        filename] + "_corrected_nuclei_seed.inr"
imsave(segmented_filename, seed_img)

seed_img = isometric_resampling(seed_img, option='label')

std_dev = 2.0
membrane_img = isometric_resampling(membrane_img)
vxs = membrane_img.voxelsize

try:
    from equalization import z_slice_contrast_stretch
    from slice_view import slice_view

except:
    import sys
    sys.path.append('/home/marie/SamMaps/scripts/TissueLab/')
    from equalization import z_slice_contrast_stretch
Beispiel #10
0
 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)
 imsave(res_path + rig_float_img_fname, res_im)
 # - Get result trsf filename:
 res_trsf_fname = get_res_trsf_fname(float_img_fname, t_ref, t_float,
                                     'iso-rigid')
 print "Writing trsf file: {}".format(res_trsf_fname)
 res_trsf.write(res_path + res_trsf_fname)
 print "\nApplying estimated {} transformation on '{}' to segmented image:".format(
     'rigid', ref_ch_name)
 if not exists(res_path + rig_seg_img_fname):
     print "  - {}\n  --> {}".format(seg_img_fname, rig_seg_img_fname)
     # --- Read the segmented image file:
     seg_im = imread(image_dirname + seg_path_suffix + seg_img_fname)
     res_seg_im = apply_trsf(seg_im,
                             res_trsf,
                             param_str_2=' -nearest -param')
     # --- Apply and save registered segmented image:
Beispiel #11
0
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,
                 vmin=0,
                 vmax=255,
                 max_per_line=2)

img2plot = [
    float_img.get_z_slice(40),
    ref_img.get_z_slice(40),
    img_rig.get_z_slice(40),
Beispiel #12
0
            res_trsf, _ = registration(list_res_img[time2index[t]],
                                       ref_im,
                                       method=trsf_type,
                                       pyramid_highest_level=py_hl,
                                       pyramid_lowest_level=py_ll)
            res_trsf = compose_trsf([trsf, res_trsf], template_img=ref_im)
            print ""
        else:
            res_trsf = trsf
            print "No need to performs supplementary round of registration for trsf_type: {}".format(
                trsf_type)

        # - Save result image and tranformation:
        print "Writing image file: {}".format(res_img_fname)
        imsave(
            dest_folder + res_img_fname,
            apply_trsf(read_image(float_img_path + float_img_fname), res_trsf))
        print "Writing trsf file: {}".format(res_trsf_fname)
        save_trsf(res_trsf, dest_folder + res_trsf_fname)
    else:
        print "Existing image file: {}".format(res_img_fname)
        print "Loading existing {} transformation file: {}".format(
            trsf_type.upper(), res_trsf_fname)
        res_trsf = read_trsf(dest_folder + res_trsf_fname)

    # -- Apply estimated transformation to other channels of the floating CZI:
    if extra_im:
        print "\nApplying estimated {} transformations to other channels...".format(
            trsf_type.upper())
        for n, x_ch_fname in enumerate(extra_im):
            # --- Defines output filename:
Beispiel #13
0
"""
This script create artificial segmented and intensity images to test the
'PIN_quantif.py' python script.
"""

from create_images import create_two_label_image
from create_images import create_two_sided_intensity_image
from create_images import create_left_sided_intensity_image
from create_images import create_right_sided_intensity_image

from timagetk.io import imsave

# - Write labelled test image:
test_label_fname = "test_seg.inr"
imsave(test_label_fname, create_two_label_image())

# - Write two-sided intensity image (PI):
test_PI_fname = "test_PI.inr"
imsave(test_PI_fname, create_two_sided_intensity_image())

# - Write left-sided intensity image (PIN1):
test_left_PIN1_fname = "test_left_PIN1.inr"
imsave(test_left_PIN1_fname, create_left_sided_intensity_image())

# - Write right-sided intensity image (PIN1):
test_right_PIN1_fname = "test_right_PIN1.inr"
imsave(test_right_PIN1_fname, create_right_sided_intensity_image())

%run ../PIN_quantif.py $test_PI_fname $test_left_PIN1_fname $test_label_fname --membrane_dist 6.
Beispiel #14
0
    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])
print("Done!\n")
# -- ISOMETRIC resampling of SEGMENTED image:
# Load the segmented image:
seg_im = imread(seg_path + seg_fname.format(t_ref, '', ext))
seg_im = isometric_resampling(seg_im, method=vxs, option='label')
# Save rigid sequence registered segmented images:
fname_res_seg = reg_path + seg_fname.format(t_ref, '', ext)
print("Saving:", fname_res_seg)
imsave(fname_res_seg, seg_im)
print("Done!\n")


# - Performs sequence registration:
list_trsf = sequence_registration(list_image, method='rigid', pyramid_lowest_level=2)
Beispiel #15
0
    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')

    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/"
Beispiel #16
0
# -- 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)
Beispiel #17
0
            # --- composition of transformations
            print "\nPerforming composition of rigid et deformable registration..."
            res_trsf = compose_trsf([trsf_rig, trsf_vf], template_img=list_iso_img[ind+1])
            list_res_trsf.append(res_trsf)
            # -- save the DEFORMABLE consecutive transformation:
            print "\nSaving {} transformation file: {}".format(trsf_type, res_trsf_fname)
            res_trsf.write(res_path + res_trsf_fname)
        # - Intensity image:
        if not exists(res_path + res_img_fname) or force:
            # -- application de la composition des transformations sur l'image
            print "\nApplying composed registration on ISO-ORIGINAL intensity image..."
            res_img = apply_trsf(isometric_resampling(imread(list_img_fname[ind])), res_trsf, template_img=list_iso_img[ind+1])
            list_res_img.append(res_img)
            # -- save the DEFORMABLE consecutive registered intensity image:
            print "\nSaving the {} registered image: {}".format(trsf_type, res_img_fname)
            imsave(res_path + res_img_fname, res_img)
        else:
            print "Loading SpatialImage:\n  {}".format(res_path + res_trsf_fname)
            res_img = imread(res_path + res_img_fname)
            list_res_img.append(res_img)
            continue

# add last reference image
list_res_img.append(list_iso_img[-1])  # add last reference image


# - Apply DEFORMABLE consecutive_registration on segmented images:
list_res_seg_img_fname = []
for ind, img in enumerate(list_iso_img[:-1]):
    # Apply DEFORMABLE consecutive registration to segmented image:
    print "\nApplying estimated {} transformation on '{}' to segmented image:".format('deformable', ref_ch_name)
Beispiel #18
0
    # -- Finaly add the background and make a SpatialImage:
    seed_img[background_img == back_id] = back_id
    seed_img = SpatialImage(seed_img, voxelsize=iso_vxs)
    del background_img
    # world.add(seed_img, "seed_image", colormap="glasbey", alphamap="constant", voxelsize=microscope_orientation*iso_vxs, background=back_id)

    # - Performs automatic seeded watershed using previously created seed image:
    print "\n - Performing seeded watershed segmentation using seed image from nuclei..."
    # -- Performs Gaussian smoothing:
    std_dev = 1.0
    smooth_img = linear_filtering(img2seg, std_dev=std_dev, method='gaussian_smoothing')
    # -- Performs the seeded watershed segmentation:
    seg_im = segmentation(smooth_img, seed_img, method='seeded_watershed')
    seg_im[seg_im == 0] = back_id
    # -- Display the segmented image:
    # world.add(seg_im, "seg_image", colormap="glasbey", alphamap="constant",voxelsize=microscope_orientation*iso_vxs, background=back_id)
    # -- Save the segmented image:
    print "Saving the segmented image: {}".format(seg_img_fname)
    imsave(image_dirname + seg_path_suffix + seg_img_fname, seg_im)
    # -- Print some info about how it went:
    labels = np.unique(seg_im)
    nb_labels = len(labels)
    seeds = np.unique(seed_img)
    nb_seeds = len(seeds)
    print "Found {} labels out of {} seeds!".format(nb_labels, nb_seeds)
    if nb_seeds - nb_labels!= 0:
        print "Missing seeds id: {}".format(set(seeds)-set(labels))

    end = int(np.ceil(time.time() - start))
    print "It took {}min {}s to performs all operations on {}!".format(end/60, end%60, raw_czi_fname)