Skip to content

Instantly share code, notes, and snippets.

@imagejan
Created February 2, 2020 21:04
Show Gist options
  • Save imagejan/3e709f2a8cc1dfff1abbdb48a2d6c208 to your computer and use it in GitHub Desktop.
Save imagejan/3e709f2a8cc1dfff1abbdb48a2d6c208 to your computer and use it in GitHub Desktop.
ImageJ script to invert RGB images with unchanged color (hue).
#@ Dataset input
#@ OpService ops
#@ DatasetService ds
#@ ConvertService cs
import net.imagej.axis.Axes
import net.imglib2.IterableInterval
import net.imglib2.type.numeric.integer.UnsignedShortType
import ij.CompositeImage
import ij.ImagePlus
import ij.IJ
// For each channel, get the average of the two other channels
ch1 = ops.convert().uint16(ops.transform().hyperSliceView(input, input.dimensionIndex(Axes.CHANNEL), 0))
ch2 = ops.convert().uint16(ops.transform().hyperSliceView(input, input.dimensionIndex(Axes.CHANNEL), 1))
ch3 = ops.convert().uint16(ops.transform().hyperSliceView(input, input.dimensionIndex(Axes.CHANNEL), 2))
nCh1 = ops.math().add(ch2, ch3 as IterableInterval)
nCh2 = ops.math().add(ch1, ch3 as IterableInterval)
nCh3 = ops.math().add(ch1, ch2 as IterableInterval)
merged16 = ops.transform().stackView([nCh1, nCh2, nCh3])
divided = ops.create().img(merged16)
divideOp = ops.op("math.divide", nCh1.firstElement(), new UnsignedShortType(2))
ops.map(divided, merged16, divideOp)
merged = ops.create().img(input)
ops.image().invert(merged, ops.convert().uint8(divided))
// stuff needed for correct display in ImageJ1
result = ds.create(merged)
imp = cs.convert(result, ImagePlus.class)
resultImage = new CompositeImage(imp.duplicate(), IJ.COMPOSITE)
resultImage.setTitle(input.getName() + "_RGBinverted")
resultImage.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment