Export 16-bit images below ROI from TrakEM2 project

Hi all,

I would like to export 16-bit images from a TrakEM2 project, but only the areas that are covered by a marked ROI (as possible for 8-bit images by the integrated „make flat image“ export function). The posted script to export 16bit images works fine ( [Exporting registered tiff stack from TrakEM2, but it takes the stack boundaries (as is stated in the script (roi = layerset.get2DBounds())). Is there a way to retrieve and use the boundary coordinates of the yellow ROI for all images of the stack instead?

For sure I could read out the coordinates of the ROI via macro recorder and crop all exported images within a folder in batch afterwards, but it would be more efficient to crop them directly during the export.

An ideas?


Hi @s.fischer,
The TrakEM2 canvas is an ImagePlus of sorts (otherwise ROIs wouldn’t work on it).
If no other image is open, do:

from ij import WindowManager as WM
roi = WM.getActiveImage().getRoi()

… or, to keep the code within TrakEM2 itself, do:

from ini.trakem2.display import Display

project = ...

front = Display.getFront(project)
roi = front.getRoi()

Then, for the roi, call roi.getBounds() to retrieve a java.awt.Rectangle that has public members x, y, width, height.

1 Like

Thanks @albertcardona for the quick response!

The TrakEM2 way works perfectly!

Attached the final script:

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

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(
           True)  # use the min and max of each tile

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

Wonderful. Thank you for sharing the final script!