Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobias/28b16ae5007f01eb8411 to your computer and use it in GitHub Desktop.
Save nobias/28b16ae5007f01eb8411 to your computer and use it in GitHub Desktop.
ImageJ/Fiji plugin: Extracts frames from a multi-frame TIFF file and saves them into a new multi-frame TIFF
import os
import os.path
import glob
from loci.plugins.util import BFVirtualStack
from loci.formats import ImageReader
from ij import ImagePlus, ImageStack
from ij import IJ
from ij.io import DirectoryChooser
from ij.gui import GenericDialog
def getOptions():
gd = GenericDialog("Options")
# show 2 decimals
gd.addStringField("Z indices to extract (comma separated)", "1,2")
gd.showDialog()
#
if gd.wasCanceled():
print "User canceled dialog!"
return
# Read out the options
z_to_extract = gd.getNextString()
return z_to_extract
def run():
# Choose a file to open
srcDir = DirectoryChooser("Choose source directory").getDirectory()
if srcDir is None:
# User canceled the dialog
return
# Choose a directory to store each slice as a file
targetDir = DirectoryChooser("Choose target directory").getDirectory()
if targetDir is None:
# User canceled the dialog
return
# Open each tif stack as a virtual BFVirtualStack
# then, extract the nth z slice and save it as a tif file in the out dir
z_to_extract = getOptions()
out_stack = False
dirlist = glob.glob(srcDir + '*.tif')
file_map = {}
for filename in dirlist:
fn, fext = os.path.splitext(filename)
nr = fn.split('X')[-1]
print nr
file_map[int(nr)] = filename
#file_map_ordered = collections.OrderedDict(sorted(file_map.items()))
for i in sorted(file_map):
for z in z_to_extract.split(','):
filename = file_map[i]
print "Reading metadata from", filename
fn, fext = os.path.splitext(filename)
ir = ImageReader()
ir.setId(filename)
bfvs = BFVirtualStack(filename, ir, False, False, False)
print z
ipr = bfvs.getProcessor(int(z))
if not out_stack:
out_stack = ImageStack(ipr.getWidth(), ipr.getHeight())
out_stack.addSlice(ipr)
print out_stack, out_stack.getSize()
print "Saving to ", targetDir + os.path.basename(fn) + '.tif'
IJ.save(ImagePlus('Concatenated stack', out_stack),
targetDir + os.path.basename(fn) + '_extracted' + '.tif')
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment