Export 16bit images from TrakEM2

Natively, TrakEM2 is only able to export 8bit images via the “Make flat image” function. However, 16bit images can be exported using the following small script.

from ini.trakem2.display import Display, Patch
from java.awt import Color

front = Display.getFront() # the active TrakEM2 display window
layer = front.getLayer()
tiles = front.getSelection().get(Patch)  # selected Patch instances only
backgroundColor = Color.black
scale = 1.0

roi = tiles[0].getBoundingBox()
for tile in tiles[1:]:
roi.add(tile.getBoundingBox())

print "Creating flat image from", len(tiles), "image tiles"

ip = Patch.makeFlatImage(
          ImagePlus.GRAY16,
           layer,
           roi,
           scale,
           tiles,
          backgroundColor,
          True)  # use the min and max of each tile

imp = ImagePlus("Flat montage", ip)
imp.show() 

If only the image part below a ROI should be used for the export, use the following script (notice that you have to change the folder path (targetDir).

from ij import ImagePlus
from ini.trakem2 import Project
from ini.trakem2.display import Patch
from ini.trakem2.display import Display
from ij.io import FileSaver
from java.awt import Color

project = Project.getProjects()[0]
layerset = project.getRootLayerSet()

front = Display.getFront(project)
roi = front.getRoi()
scale = 1.0
backgroundColor = Color.black

# NOTE: EDIT THIS PATH
targetDir = "/Users/xy/Desktop/folder"

#For other output types, use ImagePlus.GRAY8, .GRAY16, GRAY32 or .COLOR_RGB, as listed in the documentation for the ImagePlus class.

for i, layer in enumerate(layerset.getLayers()):
  print layer
  # Export the image here, e.g.:
  tiles = layer.getDisplayables(Patch)
  ip = Patch.makeFlatImage(
           ImagePlus.GRAY16,
           layer,
           roi.getBounds(),
           scale,
           tiles,
           backgroundColor,
           True)  # use the min and max of each tile

  imp = ImagePlus("Flat montage", ip)
  FileSaver(imp).saveAsTiff(targetDir + str(i + 1) + ".tif")

Source