def translate_single_stack_using_imglib2(imp, dx, dy, dz): # wrap into a float imglib2 and translate # conversion into float is necessary due to "overflow of n-linear interpolation due to accuracy limits of unsigned bytes" # see: https://github.com/fiji/fiji/issues/136#issuecomment-173831951 img = ImagePlusImgs.from(imp.duplicate()) extended = Views.extendZero(img) converted = Converters.convert(extended, RealFloatSamplerConverter()) interpolant = Views.interpolate(converted, NLinearInterpolatorFactory()) # translate if imp.getNDimensions()==3: transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz)) elif imp.getNDimensions()==2: transformed = RealViews.affine(interpolant, Translation2D(dx, dy)) else: IJ.log("Can only work on 2D or 3D stacks") return None cropped = Views.interval(transformed, img) # wrap back into bit depth of input image and return bd = imp.getBitDepth() if bd==8: return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2")) elif bd == 16: return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2")) elif bd == 32: return(ImageJFunctions.wrapFloat(cropped,"imglib2")) else: return None
def translate_single_stack_using_imglib2(imp, dx, dy, dz): # wrap into a float imglib2 and translate # conversion into float is necessary due to "overflow of n-linear interpolation due to accuracy limits of unsigned bytes" # see: https://github.com/fiji/fiji/issues/136#issuecomment-173831951 img = ImagePlusImgs.from(imp.duplicate()) extended = Views.extendBorder(img) converted = Converters.convert(extended, RealFloatSamplerConverter()) interpolant = Views.interpolate(converted, NLinearInterpolatorFactory()) # translate if imp.getNDimensions()==3: transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz)) elif imp.getNDimensions()==2: transformed = RealViews.affine(interpolant, Translation2D(dx, dy)) else: IJ.log("Can only work on 2D or 3D stacks") return None cropped = Views.interval(transformed, img) # wrap back into bit depth of input image and return bd = imp.getBitDepth() if bd==8: return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2")) elif bd == 16: return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2")) elif bd == 32: return(ImageJFunctions.wrapFloat(cropped,"imglib2")) else: return None
def samplerConvert(rai, converter): """ rai: an instance of RandomAccessibleInterval converter: an instance of a SamplerConverter. """ # Grab method through reflection. Otherwise we get one that returns an IterableInterval # which is not compatible with ImageJFunctions.wrap methods. m = Converters.getDeclaredMethod( "convert", [RandomAccessibleInterval, SamplerConverter]) return m.invoke(None, rai, converter)
def convert2(rai, converter, toType, randomAccessible=True): """ rai: an instance of RandomAccessibleInterval converter: as created with e.g. createConverter toType: class of the target Type randomAccessible: when True (default) use RandomAccessibleInterval, otherwise use IterableInterval """ # Grab method through reflection. Otherwise we get one that returns an IterableInterval # which is not compatible with ImageJFunctions.wrap methods. m = Converters.getDeclaredMethod("convert", [ RandomAccessibleInterval if randomAccessible else IterableInterval, Converter, ImgLib2Type ]) return m.invoke(None, rai, converter, toType.newInstance())
def translate_using_imglib2(imp, dx, dy, dz): print "imp channels",imp.getNChannels() # todo: # if multiple channels use Duplicator to translate each channel individually ## wrap # http://javadoc.imagej.net/ImgLib2/net/imglib2/img/imageplus/ImagePlusImg.html img = ImagePlusImgs.from(imp.duplicate()) print "dimensions:",img.numDimensions() print img.getChannels() ## prepare image print "img",img ddd extended = Views.extendBorder(img) #print "extended",extended #print "extended",extended.dimension(1) dims = zeros(4, 'l') img.dimensions(dims) print "dims",dims converted = Converters.convert(extended, RealFloatSamplerConverter()) composite = Views.collapseReal(converted, imp.getNChannels()) print "composite",composite interpolant = Views.interpolate(composite, NLinearInterpolatorFactory()) #print "interpolant",interpolant transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz)) print "transformed", transformed cropped = Views.interval(transformed, img) print "cropped.numDimensions()", cropped.numDimensions() print "cropped",cropped ## wrap back and return bd = imp.getBitDepth() # maybe simply wrap works? if bd==8: return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2")) elif bd == 16: return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2")) elif bd == 32: return(ImageJFunctions.wrapFloat(cropped,"imglib2")) else: return None
from net.imglib2.type.numeric.real import FloatType from net.imglib2.type.numeric.complex import ComplexFloatType from net.imglib2.util import Intervals from java.util.concurrent import Executors from java.lang import Runtime from java.awt import Rectangle from net.imglib2.img.display.imagej import ImageJFunctions as IL from ij import IJ # Open Nile Bend sample image imp = IJ.getImage() #imp = IJ.openImage("https://imagej.nih.gov/ij/images/NileBend.jpg") img = IL.wrapRGBA(imp) # Extract red channel: alpha:0, red:1, green:2, blue:3 red = Converters.argbChannel(img, 1) # Cut out two overlapping ROIs r1 = Rectangle(1708, 680, 1792, 1760) r2 = Rectangle(520, 248, 1660, 1652) cut1 = Views.zeroMin( Views.interval(red, [r1.x, r1.y], [r1.x + r1.width - 1, r1.y + r1.height - 1])) cut2 = Views.zeroMin( Views.interval(red, [r2.x, r2.y], [r2.x + r2.width - 1, r2.y + r2.height - 1])) # Thread pool exe = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) try:
LoopBuilder.setImages(red, green, img_sub).forEachPixel(Consumer()) IL.wrap(img_sub, "LoopBuilder").show() """ # Example 2b: with ImgLib2 LoopBuilder using a clojure-defined TriConsumer from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.converter import Converters from net.imglib2.img.array import ArrayImgs from net.imglib2.util import Intervals from net.imglib2.loops import LoopBuilder from org.scijava.plugins.scripting.clojure import ClojureScriptEngine img = IL.wrap(imp_rgb) # an ARGBType Img red = Converters.argbChannel(img, 1) # a view of the ARGB red channel green = Converters.argbChannel(img, 2) # a view of the ARGB green channel img_sub = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img)) # the img to store the result code = """ (deftype Consumer [^long threshold] %s (accept [self red green result] ; can't type-hint, doesn't find matching method (let [^%s r red ^%s g green ^%s s result] (.setInteger s (if (>= (.getInteger r) threshold) (.getInteger g) 0))))) """ % ((LoopBuilder.TriConsumer.getName(),) \ + tuple(a.randomAccess().get().getClass().getName() for a in [red, green, img_sub]))
from net.imglib2.algorithm.math.ImgMath import compute, maximum from net.imglib2.converter import Converters, ColorChannelOrder from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.view import Views from ij import IJ, ImagePlus # Fetch an RGB image stack (or any RGB image with more than 1 dimension) imp_rgb = IJ.getImage( ) # IJ.openImage("http://imagej.nih.gov/ij/images/flybrain.zip") img = IL.wrap(imp_rgb) # an ARGBType Img red = Converters.argbChannel(img, 1) # a view of the ARGB red channel # Project the last dimension using the max function last_d = red.numDimensions() - 1 op = maximum( [Views.hyperSlice(red, last_d, i) for i in xrange(red.dimension(last_d))]) img_max_red = compute(op).intoArrayImg() IL.wrap(img_max_red, "max projection of the red channel)").show() # Now project all 3 color channels and compose an RGB image last_dim_index = img.numDimensions() - 1 channel_stacks = [[ Views.hyperSlice(Converters.argbChannel(img, channel_index), last_dim_index, slice_index) for slice_index in xrange(img.dimension(last_dim_index)) ] for channel_index in [1, 2, 3]] # 1: red, 2: green, 3: blue channels = Views.stack([maximum(cs).view() for cs in channel_stacks]) max_rgb = Converters.mergeARGB(channels, ColorChannelOrder.RGB)
def testASM(): ImgUtil.copy( ImgView.wrap( Converters.convertRandomAccessibleIterableInterval( img1, samplerClass.newInstance()), img1.factory()), img2)
interval2 = FinalInterval([ int(img1.dimension(0) * scale), int(img1.dimension(1) * scale), img1.dimension(2) ]) # Interval of a single stack slice of the target image sliceInterval = FinalInterval([interval2.dimension(0), interval2.dimension(1)]) slices2 = [] for index in xrange(img1.dimension(2)): # One single 2D RGB slice imgSlice1 = Views.hyperSlice(img1, 2, index) # Views of the 3 color channels, as extended and interpolatable channels = [ Views.interpolate( Views.extendZero(Converters.argbChannel(imgSlice1, i)), NLinearInterpolatorFactory()) for i in [1, 2, 3] ] # ARGBType 2D view of the transformed color channels imgSlice2 = Converters.mergeARGB( Views.stack( Views.interval(RealViews.transform(channel, transform), sliceInterval) for channel in channels), ColorChannelOrder.RGB) slices2.append(imgSlice2) # Transformed view viewImg2 = Views.stack(slices2) # Materialized image img2 = ArrayImgs.argbs(Intervals.dimensionsAsLongArray(interval2)) ImgUtil.copy(viewImg2, img2)
def iterableChannel(imgARGB, i): return Views.iterable(Converters.argbChannel(imgARGB, i))
from net.imglib2.img.array import ArrayImgFactory from net.imglib2.type.numeric.real import FloatType from itertools import izip from ij import IJ # # Load an RGB or ARGB image imp = IJ.getImage() # Access its pixel data from an ImgLib2 data structure: # a RandomAccessibleInterval<ARGBType> img = IL.wrapRGBA(imp) # Convert an ARGB image to a stack of 4 channels: a RandomAccessibleInterval<UnsignedByte> # with one more dimension that before. # The order of channels in the stack can be changed by changing their indices. channels = Converters.argbChannels(img, [0, 1, 2, 3]) impChannels = IL.wrap(channels, imp.getTitle() + " channels") impChannels.show() # Read out a single channel directly red = Converters.argbChannel(img, 1) # Pick a view of the red channel in the channels stack. # Takes the last dimension, which are the channels, # and fixes it, pointing to the index of the red channel (1) in the stack. red = Views.hyperSlice(channels, channels.numDimensions() -1, 1) impRed = IL.wrap(red, imp.getTitle() + " - red channel") impRed.show()
pixels = ip.getPixels() # In practice, you never want to do this below, # and instead you'd use the built-in wrapper: ImageJFunctions.wrap(imp) # This is merely for illustration of how to use ArrayImgs with an existing pixel array if isinstance(ip, ByteProcessor): img1 = ArrayImgs.unsignedBytes(pixels, dimensions) elif isinstance(ip, ShortProcessor): img1 = ArrayImgs.unsignedShorts(pixels, dimensions) elif isinstance(ip, FloatProcessor): img1 = ArrayImgs.floats(pixels, dimensions) else: print "Can't handle image of type:", type(ip).getName() # An empty image of float[] img2 = ArrayImgs.floats(dimensions) # View it as RandomAccessibleInterval<FloatType> by converting on the fly # using a generic RealType to FloatType converter floatView = Converters.convertRAI(img1, RealFloatConverter(), FloatType()) # The above 'floatView' can be used as an image: one that gets always converted on demand. # If you only have to iterate over the pixels just once, there's no need to create a new image. IL.show(floatView, "32-bit view of the 8-bit") # Copy one into the other: both are of the same type ImgUtil.copy(floatView, img2) IL.show(img2, "32-bit copy")
from ij import IJ from net.imglib2.algorithm.math.ImgMath import compute, maximum, minimum, log, exp, div, mul from net.imglib2.algorithm.math import Print from net.imglib2.converter import Converters, ColorChannelOrder from net.imglib2.img.array import ArrayImgs from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.view import Views # Fetch an RGB image stack imp_rgb = IJ.getImage( ) # IJ.openImage("http://imagej.nih.gov/ij/images/flybrain.zip") img = IL.wrap(imp_rgb) # an ARGBType Img # Color channel views red, green, blue = (Converters.argbChannel(img, c) for c in [1, 2, 3]) # ImgLib1 scripting gamma function # return Min(255, Max(0, Multiply(Exp(Multiply(gamma, Log(Divide(channel, 255)))), 255))) gamma = 0.5 def op(channel): return minimum( 255, maximum(0, mul(exp(mul(gamma, log(div(channel, 255)))), 255))) img_gamma = Converters.mergeARGB( Views.stack( op(red).viewDouble(), op(green).viewDouble(),
def testASMDoubles(): img2 = ArrayImgs.doubles(dimensions) ImgUtil.copy( ImgView.wrap( Converters.convertRandomAccessibleIterableInterval( img1, sampler_conv_doubles), img1.factory()), img2)
from net.imglib2.img.array import ArrayImgFactory from net.imglib2.type.numeric.real import FloatType from net.imglib2.type.numeric.integer import UnsignedByteType from net.imglib2.algorithm.math.ImgMath import compute, maximum, minimum, div, let, var, IF, THEN, ELSE, EQ, sub from ij import IJ # Load an RGB or ARGB image #imp = IJ.openImage("https://imagej.nih.gov/ij/images/leaf.jpg") imp = IJ.getImage() # Access its pixel data from an ImgLib2 data structure: # a RandomAccessibleInterval<ARGBType> img = IL.wrapRGBA(imp) # Read out single channels red = Converters.argbChannel(img, 1) green = Converters.argbChannel(img, 2) blue = Converters.argbChannel(img, 3) # Create an empty image of type FloatType (floating-point values) # Here, the img is used to read out the interval: the dimensions for the new image brightness = ArrayImgFactory(FloatType()).create(img) # Compute the brightness: pick the maximum intensity pixel of every channel # and then normalize it by dividing by the number of channels compute(div(maximum([red, green, blue]), 255.0)).into(brightness) # Show the brightness image impB = IL.wrap(brightness, imp.getTitle() + " brightness") impB.show()
def testASMLongs(): img2 = ArrayImgs.unsignedLongs(dimensions) ImgUtil.copy( ImgView.wrap( Converters.convertRandomAccessibleIterableInterval( img1s, sampler_conv_longs), img1.factory()), img2)
def testJython(): ImgUtil.copy( ImgView.wrap( Converters.convertRandomAccessibleIterableInterval( img1, UnsignedByteToFloatSamplerConverter()), img1.factory()), img2)
from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.algorithm.math.ImgMath import let, IF, EQ, LT, THEN, ELSE, add, div, sub, maximum, minimum, compute, img from net.imglib2.algorithm.math.abstractions.Util import hierarchy from net.imglib2.converter import Converters from net.imglib2.type.numeric.real import FloatType from net.imglib2.view import Views from net.imglib2.img.array import ArrayImgs from net.imglib2.util import ImgUtil from net.imglib2.img import ImgView from java.lang import System from jarray import zeros from itertools import izip rgb = IL.wrap(IJ.getImage()) red = Converters.argbChannel(rgb, 1) green = Converters.argbChannel(rgb, 2) blue = Converters.argbChannel(rgb, 3) def test(red, green, blue, easy=True): saturation = let( "red", red, "green", green, "blue", blue, "max", maximum("red", "green", "blue"), "min", minimum("red", "green", "blue"), IF(EQ(0, "max"), THEN(0), ELSE(div(sub("max", "min"), "max")))) brightness = div(maximum(red, green, blue), 255.0) hue = IF( EQ(0, saturation), THEN(0),