Skip to content

Instantly share code, notes, and snippets.

@GenevieveBuckley
Last active January 9, 2018 06:12
Show Gist options
  • Save GenevieveBuckley/db55b6c314fa02973542c110dbf0d491 to your computer and use it in GitHub Desktop.
Save GenevieveBuckley/db55b6c314fa02973542c110dbf0d491 to your computer and use it in GitHub Desktop.
Watershed methods using Jython scripting and the ImageJ/ImgLib2/MorphoLibJ APIs. http://javadoc.scijava.org
"""Calculating the gradient image that needs to go into Watershed."""
from ij import IJ
# operates on ImagePlus object: imp
IJ.run(imp, "Gradient (3D)", "use")
# modifies imp, returns None.
# YOU MUST MAKE A COPY OF IMP BEFORE YOU RUN THIS!
# This method also automatically displays the modified gradient image (unless you suppress it).
# Output image name is always "Rebinned" - change it to something better afterwards.
# @OpService ops
from ij import IJ, ImagePlus
from net.imglib2.img import ImagePlusAdapter
from inra.ijpb.watershed import Watershed
from net.imglib2.roi.labeling import LabelRegions, LabelRegion, BoundingBox
from net.imglib2.algorithm.labeling.ConnectedComponents import StructuringElement
edges = IJ.openImage() # opens file picker
seeds = IJ.openImage() # opens file picker
output_watershed = Watershed().computeWatershed(edges.getStack(), seeds.getStack(), 26) # pixel connectivity = 26
output_ImagePlus = ImagePlus("Watershed result", output_watershed) # to ImagePlus (from stack type)
output_ImagePlus.show()
output_ImgPlus = ImagePlusAdapter.wrapImgPlus(output_ImagePlus) # to ImgPlus
# MUST convert watershed output into binary image, or else len(labelSet) = 0 !
watershed_binary_image = ops.run("convert.bit", output_ImgPlus) # to binary type ImgPlus
labels = ops.labeling().cca(watershed_binary_image, StructuringElement.EIGHT_CONNECTED) # returns ImgLabeling object
regions = LabelRegions(labels) # returns regions found from labels of connected components analysis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment