Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
1 result

Target

Select target project
No results found
Select Git revision
  • master
1 result
Show changes

Commits on Source 17

6 files
+ 1879
227
Compare changes
  • Side-by-side
  • Inline

Files

Original line number Original line Diff line number Diff line
@@ -8,6 +8,12 @@
  ```
  ```
  with your path to the folder containing the folder **utils**, (i.e. the path where you have unzip the package)
  with your path to the folder containing the folder **utils**, (i.e. the path where you have unzip the package)
  
  
## Install as a FiJi Plugins

1. Locate the folder where your ImageJ is installed
2. Add a folder **disco_ij** in the **Fiji.app/plugins** folder an copy the **script_mosaic_telemos.py** into the **disco_ij** folder.
3. Copy the **utils** folder into **Fiji.app/jars/Lib** directory
4. In Fiji **help>refresh menus** and **restart FiJi*


# Procedure
# Procedure
  - Open FIJI
  - Open FIJI
+73 −0
Original line number Original line Diff line number Diff line
# -*- coding: utf-8 -*-
"""
Usefull jython functions for micro manager and imagej
"""
import os
from ij import ImagePlus, VirtualStack, IJ
from mmlib import generate_file_list, load_metadata, get_dimensions, get_resolution, get_micromanager_version


def load_mm_images(rootdir, roi=1, tile=True, pos=False, 
                   return_filenames=False):
    """
    Use the metadata and mmlib's functions to load images 
    files into an ImageJ VirtualStack
    """
    
    if tile:
        metadata = load_metadata(os.path.join(rootdir, 'roi%i_tile1'%int(roi), 'metadata.txt'))
    else:
        metadata = load_metadata(rootdir)
        
    mmversion = int(get_micromanager_version(metadata)[0])
    dimensions = get_dimensions(metadata, roi)
    if mmversion == 1:
        stack_order = ['position', 'z', 'time', 'channels']
    else:
        stack_order = ['position', 'time', 'channels', 'z']

    if not tile and pos:
        stack_order = ['position', 'time', 'z', 'channels']
    image_files = generate_file_list(metadata, roi, tile, pos, stack_order)
    
    # Create the virtual stack
    vstack = VirtualStack(dimensions['width'], dimensions['height'], None, rootdir)
    
    # Loop over slides
    for imgname in image_files:
        vstack.addSlice(imgname)
        
        if not os.path.isfile(os.path.join(rootdir,imgname)):
            print('file %s does not exist' % imgname)

    # Create the ImagePlus to display the stack
    imp = ImagePlus("%s" % rootdir, vstack)

    # dim starts at one in java not zero
    # Size of channels
    nchannel = dimensions['channels']
    # Size of z 
    nslice = dimensions['z']
    
    # The rest of dimensions goes to time
    nother = (dimensions['time']) * (dimensions['position'])

    imp.setDimensions(nchannel, nslice, nother)
    imp.setOpenAsHyperStack(True)
    
    reso = get_resolution(metadata)
    
    # Try to set the physical size from Metadata
    try:
        IJ.run(imp,
               "Properties...",
               "pixel_width={reso} pixel_height={reso} pixel_unit='um'".format(reso=reso))
    except:
        pass
        
    # Set auto contrast
    IJ.run(imp, "Enhance Contrast", "saturated=0.35")
    if return_filenames:
        return imp, image_files
    else:
        return imp
Original line number Original line Diff line number Diff line
# -*- coding: utf-8 -*-
"""
"""
Contain function or class to make import of image sequences easier in ImageJ
Contain function or class to make import of image sequences easier in ImageJ
"""
"""
@@ -14,6 +13,8 @@ from ij import ImagePlus, VirtualStack, IJ
def load_image_sequence(rootdir, path_pattern, order=None, channel_group=None,
def load_image_sequence(rootdir, path_pattern, order=None, channel_group=None,
                        z_group=None, return_filenames=False):
                        z_group=None, return_filenames=False):
    """
    """
    THIS ONE IS BUGGY FOR MM2 format
    
    Load an image sequence (several tiff files in several sub-folders) as an ImageJ VirtualStack.
    Load an image sequence (several tiff files in several sub-folders) as an ImageJ VirtualStack.
    It uses the python string format to define the pattern of file names
    It uses the python string format to define the pattern of file names
    If order is specified as a list of pattern keys, image will be loaded in that order,
    If order is specified as a list of pattern keys, image will be loaded in that order,
@@ -106,6 +107,8 @@ def load_image_sequence(rootdir, path_pattern, order=None, channel_group=None,
    vstack = VirtualStack(width, height, None, rootdir)
    vstack = VirtualStack(width, height, None, rootdir)
    for imgname in allnames:
    for imgname in allnames:
        vstack.addSlice(imgname)
        vstack.addSlice(imgname)
        if not os.path.isfile(os.path.join(rootdir,imgname)):
            print('file %s does not exist' % imgname)


    # Create the ImagePlus to display the stack
    # Create the ImagePlus to display the stack
    imp = ImagePlus("%s" % rootdir, vstack)
    imp = ImagePlus("%s" % rootdir, vstack)

ImageJ/utils/mmlib.py

0 → 100644
+263 −0
Original line number Original line Diff line number Diff line
# -*- coding: utf-8 -*-
"""
Some usefull functions to deal with micro-manager generated file structures in
python
"""
import glob
import json
import os
import re
from itertools import product
from collections import namedtuple


def load_metadata(metadata_file):
    """
    Load micro-manager metadata and return a dictionnary with those metadata.

    metadata_file of micromanager metadata.txt could be a file or a root_folder
    """

    if metadata_file.endswith('metadata.txt'):
        input_file = metadata_file
    else:
        # use glob to open the first metadata.txt
        input_file = sorted(glob.glob(os.path.join(metadata_file, '**', 'metadata.txt')))[0]

    metad = json.load(open(input_file))

    return metad


def get_resolution(metadata):
    """
    Return the physical resolution defined in metadata summary
    """
    
    v = get_micromanager_version(metadata)
    if v[0] == '2':
        # MM2 version
        fmeta = get_mm2_first_image_metadata(metadata)
        scale=fmeta['PixelSizeUm']
    else:
        # MM1 version
        scale = metadata['Summary']['PixelSize_um']
        
    return scale


def get_micromanager_version(metadata):
    """
    Return the version of micro-manager
    """
    return metadata['Summary']['MicroManagerVersion'].split('.')


def get_mm2_first_image_metadata(metadata):
    """
    Return the first metadata in the list of images starting with Metadata
    """

    for k in metadata.keys():
        if k.startswith('Metadata-'):
            return metadata[k]

    return None


def get_mm1_first_image_metadata(metadata):
    """
    Return the first metadata in the list of images starting with Metadata
    """

    for k in metadata.keys():
        if k.startswith('FrameKey-'):
            return metadata[k]

    return None
    
def get_mm_first_image_metadata(metadata):
    """
    Return the first metadata in the list of images starting with Metadata
    """
    
    v = get_micromanager_version(metadata)
    
    if v[0] == '1':
        return get_mm1_first_image_metadata(metadata)
        
    return get_mm2_first_image_metadata(metadata)
    
def get_dimensions(metadata, roi=None, pos=None):
    """
    Extract from metadata the dimensions of data and export a consistent
    dictionnary
    """

    summary = metadata['Summary']

    v = get_micromanager_version(metadata)

    dimensions = {
        'time': summary['Frames'],
        'z': summary['Slices'],
        'channels': summary['Channels']
    }
    
    # Positions defined in 'Summary' is the sum of all roiXX positions...
    if roi is None and pos is None:
        dimensions['position'] = summary['Positions']
        
    if roi is not None:
        roi = int(roi)
        dimensions['position'] = len([m['Label'] for m in metadata['Summary']['StagePositions'] if m['Label'].startswith('roi%i'%roi)])
        
    
    # Special cases for size
    if v[0] == '1':
        dimensions['width'] = summary['Width']
        dimensions['height'] = summary['Height']

    else:
        first_file_metad = get_mm2_first_image_metadata(metadata)
        dimensions['width'] = first_file_metad['Width']
        dimensions['height'] = first_file_metad['Height']

    return dimensions
    
    
def get_position_index(metadata, roi=1):
    """
    Get the starting position index for this tile
    """
    
    roi = int(roi)
    for k in metadata.keys():
        if k.startswith('Coords-roi%i_tile1'%roi):
            start_index = metadata[k]['PositionIndex']
            return start_index
    
    return 0
            

def groups_dimensions(metadata, roi=None, ordered_keys = None):
    """
    Create a list of all possible combinations of dimensions.

    Exemple:
    --------

    # time = [0,1]
    # position = [0, 1, 2]

    groups_dimensions(metadata)
    -> ((0,0,0,0),
        (0,1,0,0),
        (0,2,0,0),
        (1,0,0,0),
        (1,1,0,0),
        (1,2,0,0))

        ['position', 'time', 'channels', 'z']

    """

    if ordered_keys is None:
        ordered_keys = ['position', 'time', 'channels', 'z']

    dims = get_dimensions(metadata, roi)
    dims2 = dict(zip(ordered_keys, [list(range(dims[k])) for k in ordered_keys]))
    all_groups = list(product(*(dims2[k] for k in ordered_keys)))

    return all_groups, ordered_keys


def get_stage_positions_labels(metadata):
    """
    Return the name (which is the name of the folder) that contains each files
    """

    v = get_micromanager_version(metadata)

    stage_label = []

    if v[0] == '2':
        for sp in metadata['Summary']['StagePositions']:
            stage_label += [ sp['Label'] ]

    if v[0] == '1':
        for sp in metadata['Summary']['InitialPositionList']:
            stage_label += [ sp['Label'] ]

    return stage_label


def generate_file_list(metadata, roi=1, tile=True, pos=False, stack_order=None):
    """
    Generate a list of all images to load from the metadata

    Manage mode
    tile and pos

    MM2:
        file_fmt = img_channel{filter:003d}_position{tile:003d}_time{time:009d}_z{z:003d}.tif

    MM1:
        file_fmt = img_000000000_{filter}_{z:003d}.tif

    For tile:
        roi{roi}_tileXX/file_fmt

    For pos:
        roi{roi}-Pos_{row}_{cols}/file_fmt
    """

    fmtMM1 = 'img_{time:009d}_{filter}_{z:003d}.tif'
    fmtMM2 = 'img_channel{filter:003d}_position{pos:003d}_time{time:009d}_z{z:003d}.tif'

    v = get_micromanager_version(metadata)
    chNames = metadata['Summary']['ChNames']

        
    # Need to get the default folder for the position
    if v[0] == '1':
        pre_folder = 'Pos0'
    else:
        pre_folder = 'Default' # Is redefined
        
    # Get the combination of all conditions of acquisitions
    all_conditions, ordered_keys = groups_dimensions(metadata, roi, stack_order)

    # Loop over conditions to create the correct file name
    image_files = []
    for group in all_conditions:
    
        if tile:
            pre_folder = 'roi{roi}_tile{tile:d}'
            pre_folder = pre_folder.format(roi=roi,
                                           tile=group[ordered_keys.index('position')]+1)
                                           
        if v[0] == '2':
            if tile:
                min_pos_index = get_position_index(metadata, roi)
            else:
                min_pos_index = 0
                
            if pos:
                # Define the pre_folder
                pre_folder = 'Pos{i}'.format(i=group[ordered_keys.index('position')])
                         
            base_fmt = fmtMM2.format(filter=group[ordered_keys.index('channels')],
                                     pos=group[ordered_keys.index('position')]+min_pos_index,
                                     time=group[ordered_keys.index('time')],
                                     z=group[ordered_keys.index('z')])
        else:
            base_fmt = fmtMM1.format(filter=chNames[group[ordered_keys.index('channels')]],
                                     time=group[ordered_keys.index('time')],
                                     z=group[ordered_keys.index('z')])



        image_files += [os.path.join(pre_folder,base_fmt)]

    return image_files