convert_ometiff.py 2.09 KB
Newer Older
Christoph Sommer's avatar
Christoph Sommer committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
import os
import re
import sys
import glob
import numpy
import argparse
import tifffile

import warnings
warnings.filterwarnings("ignore")

__author__ = "christoph.sommer@ist.ac.at"
__licence__ = "GPLv3"
__version__ = "0.1.0"

description = \
"""
Convert multi-file OME-Tiff files produced at Open-SPIM microscope to ImageJ hyper-stacks
"""
        
pat = r'spim_dataset_CH_(?P<channel>.+)_TL(?P<frame>.+)_Angle0.ome.tiff'

def get_args():
    parser = argparse.ArgumentParser(
        description=description)
    
    parser.add_argument('input_folders', type=str, nargs='+', help="List of input folders containing OME-Tiff files")

    return parser.parse_args()

def convert(in_dir):
    assert os.path.exists(in_dir), "Folder does not exist '{}'".format(in_dir)

    ome_fns = glob.glob(os.path.join(in_dir, "*.ome.tiff"))

    assert len(ome_fns) > 0, "No ome.tiff files found in {}'".format(in_dir)

    # read first for spatial dims from frist file
    tmp = tifffile.imread(ome_fns[0], is_ome=False)

    dtype = tmp.dtype
    z, y, x = tmp.shape

    channel_set = set()
    frame_set = set()

    fn_lkp = {}
    for fn in ome_fns:
        fn_base = os.path.basename(fn)
        match = re.search(pat, fn_base)
        groupdict = match.groupdict()
        channel = groupdict["channel"]
        frame = groupdict["frame"]
        
        fn_lkp[(channel, frame)] = fn

        channel_set.add(channel)
        frame_set.add(frame)
    
    out_hyper = numpy.zeros((len(frame_set), z, len(channel_set), y, x), dtype=dtype)

    print("Output shape TZCYX", out_hyper.shape)

    for c, channel in enumerate(sorted(channel_set)):
        for f, frame in enumerate(sorted(frame_set, key=lambda t: int(t))):
            print("Reading", fn_lkp[(channel, frame)], c, f)
            tmp = tifffile.imread(fn_lkp[(channel, frame)], is_ome=False)
            out_hyper[f, :, c, :, :] = tmp

    out_fn = "Resaved.tif"
    print("Resaving to", out_fn)
    tifffile.imsave(os.path.join(in_dir, out_fn), out_hyper, imagej=True)

def main():
    args = get_args()

    for in_dir in args.input_folders:
        convert(in_dir)