def to8bitRange(values): # Ensure the value is inside [minimum, maximum] range, then rezero by subtracting minimum, and divide by span (maximum - minimum) return [ UnsignedByteType( int(((min(max(val, minimum), maximum) - minimum) / span) * range_max)) for val in values ]
def SpotDetectionRedFromHue(hue, data, ops, display): # get the dimensions dimensions2D=array( [hue.dimension(0), hue.dimension(1)], 'l') shift=UnsignedByteType() shift.setReal(-50) hue_shift=ops.add(hue, shift) display.createDisplay("shift", data.create(ImgPlus(hue_shift))) #test1=ops.op("otsu", hue_shift) manualthreshold=Manual() # apply the threshold operation thresholded=ops.run("threshold", ops.create( dimensions2D, BitType()), hue_shift, manualthreshold) #thresholded=ops.run("threshold", ops.create( dimensions2D, BitType()), hue_shift, Otsu()) return thresholded
def createType(bytesPerPixel): if 1: return UnsignedByteType() if 2: return UnsignedShortType() if 4: return FloatType() if 8: return UnsignedLongType()
def SpotDetectionRedFromHue(hue, data, ops, display): # get the dimensions dimensions2D = array([hue.dimension(0), hue.dimension(1)], 'l') shift = UnsignedByteType() shift.setReal(-50) hue_shift = ops.add(hue, shift) display.createDisplay("shift", data.create(ImgPlus(hue_shift))) #test1=ops.op("otsu", hue_shift) manualthreshold = Manual() # apply the threshold operation thresholded = ops.run("threshold", ops.create(dimensions2D, BitType()), hue_shift, manualthreshold) #thresholded=ops.run("threshold", ops.create( dimensions2D, BitType()), hue_shift, Otsu()) return thresholded
def rescale_uint8(ops, img): """ Rescale input image (imglib2) to full uint8 range """ scale_op = NormalizeScaleRealTypes() scale_op.setEnvironment(ops) scale_op.initialize() out_uint8 = ArrayImgFactory(UnsignedByteType()).create(img) ops.convert().imageType(out_uint8, img, scale_op) return out_uint8
class MandelbrotRealRandomAccess(RealRandomAccess): def __init__(self): self.t = UnsignedByteType() self.pos = zeros(2, 'd') def get(self): self.t.set(M.mandelbrot(self.pos[0], self.pos[1], 255)) return self.t def copyRealRandomAccess(self): return self.copy() def copy(self): a = MandelbrotRealRandomAccess() a.pos[0] = self.pos[0] a.pos[1] = self.pos[1] return a def localize(self, position): position[0] = self.pos[0] position[1] = self.pos[1] def getFloatPosition(self, d): return Float(self.pos[d]) def getDoublePosition(self, d): return self.pos[d] def move(self, distance, d): pass # many overlapping homonimous methods def setPosition(self, position): # ignore RealLozalizable instances of "position" self.pos[0] = position[0] self.pos[1] = position[1] def setPosition(self, position, d): self.pos[d] = position
def testRectangle(self): # create a test image with a filled rectangle testImg = ops.run("create.img", [256, 256], UnsignedByteType()) formula = "(p[0]>10 && p[0]<110 && p[1]>10 && p[1]<110)*255" ops.image().equation(testImg, formula) edgesImage = findEdges(testImg); ra = edgesImage.randomAccess() ra.setPosition([9, 9]) v1 = ra.get().get() ra.setPosition([10, 10]) v2 = ra.get().get() ra.setPosition([11,11]) v3 = ra.get().get() ra.setPosition([12,12]) v4 = ra.get().get() self.assertEquals(v1, 0) self.assertEquals(v2, 64) self.assertEquals(v3, 255) self.assertEquals(v4, 0)
from net.imglib2.img.array import ArrayImgFactory from net.imglib2.type.numeric.integer import UnsignedByteType, UnsignedShortType from net.imglib2.util import Intervals # An 8-bit 256x256x256 volume img = ArrayImgFactory(UnsignedByteType()).create([256, 256, 256]) # Another image of the same type and dimensions, but empty img2 = img.factory().create( [img.dimension(d) for d in xrange(img.numDimensions())]) # Same, but easier reading of the image dimensions img3 = img.factory().create(Intervals.dimensionsAsLongArray(img)) # Same, but use an existing img as an Interval from which to read out the dimensions img4 = img.factory().create(img) # Now we change the type: same kind of image and same dimensions, # but crucially a different pixel type (16-bit) via a new ImgFactory imgShorts = img.factory().imgFactory(UnsignedShortType()).create(img)
from net.imglib2.algorithm.math.ImgMath import compute, gen from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.type.numeric.integer import UnsignedByteType from net.imglib2.img.array import ArrayImgs from net.imglib2.util import Intervals from net.imglib2 import KDTree, Point locations = [(10, 15), (25, 40), (30, 75), (80, 60)] points = [ Point.wrap([x, y]) for x, y in [(10, 15), (25, 40), (30, 75), (80, 60)] ] values = [UnsignedByteType(v) for v in [128, 164, 200, 255]] kt = KDTree(values, points) dimensions = [100, 100] op = gen(kt, 10) target = ArrayImgs.unsignedBytes( Intervals.dimensionsAsLongArray(op.getInterval())) compute(op).into(target) IL.wrap(target, "KDTree").show()
def __init__(self): self.t = UnsignedByteType() self.pos = zeros(2, 'd')
def intoImg(pixels): img = ArrayImgFactory(UnsignedByteType()).create([4, 4]) System.arraycopy(pixels, 0, img.update(None).getCurrentStorageArray(), 0, len(pixels)) return img
table.addValue("y", p[1]) table.addValue("sum", s) table.show("Embryo intensities at peaks") # Now show an image with white circles for every embryo found # We'll use a sparse image: an image that doesn't have a data point for each pixel # but instead has a function for generating pixel data from the x,y coordinates of each embryo from net.imglib2 import KDTree, RealPoint, RealRandomAccess, RealRandomAccessible from net.imglib2.neighborsearch import NearestNeighborSearchOnKDTree from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.type.numeric.integer import UnsignedByteType from java.util import AbstractList inside = UnsignedByteType(255) outside = UnsignedByteType(0) radius = 30 # = sigmaLarger, where sigmaLarger is the radius of the embryo centers = dog.getSubpixelPeaks() # in floating-point coordinates class ConstantValueList(AbstractList): def __init__(self, constantvalue, count): self.constantvalue = constantvalue self.count = count def get(self, index): return self.constantvalue def size(self): return self.count
# Make any non-zero pixel be 1 for t in img1: if 0 != t.getIntegerLong(): t.setOne() for t in img2: if 0 != t.getIntegerLong(): t.setOne() # Make both fit within the same window, centered dims1 = Intervals.dimensionsAsLongArray(img1) dims2 = Intervals.dimensionsAsLongArray(img2) dims3 = [max(a, b) for a, b in izip(dims1, dims2)] zero = UnsignedByteType(0) img1E = Views.extendValue(img1, zero) img2E = Views.extendValue(img2, zero) img1M = Views.interval( img1E, [(dim1 - dim3) / 2 for dim1, dim3 in izip(dims1, dims3)], [dim1 + (dim3 - dim1) / 2 - 1 for dim1, dim3 in izip(dims1, dims3)]) img2M = Views.interval( img2E, [(dim2 - dim3) / 2 for dim2, dim3 in izip(dims2, dims3)], [dim2 + (dim3 - dim2) / 2 - 1 for dim2, dim3 in izip(dims2, dims3)]) IL.show(img1M, "img1M") IL.show(img2M, "img2M") # Scale by half (too slow otherwise) -- ERROR: the smaller one (img1) doesn't remain centered.
class Loader(ClassLoader): def defineClass(self, name, bytes): # Inheritance of protected methods is complicated in jython m = super(ClassLoader, self).__thisclass__.getDeclaredMethod("defineClass", String, Class.forName("[B"), Integer.TYPE, Integer.TYPE) m.setAccessible(True) return m.invoke(self, name.replace("/", "."), bytes, 0, len(bytes)) clazz = Loader().defineClass(class_name, cw.toByteArray()) """ loader = ClassLoader.getSystemClassLoader() defineClass = loader.getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("defineClass", String, Class.forName("[B"), Integer.TYPE, Integer.TYPE) defineClass.setAccessible(True) bytes = cw.toByteArray() clazz = defineClass.invoke(loader, class_name.replace("/", "."), bytes, 0, len(bytes)) """ bt = UnsignedByteType(120) ft = FloatType() conv = clazz.newInstance() conv.convert(bt, ft) print ft
width = img.dimension(0) min_width = 32 imgE = Views.extendBorder(integralImg) blockSide = 1 # Corners for level 1: a box of 2x2 corners = [[0, 0], [1, 0], [0, 1], [1, 1]] pyramid = [] # level 0 is the image itself, not added while width > min_width: blockSide *= 2 width /= 2 # Scale the corner coordinates to make the block larger cs = [[c * blockSide for c in corner] for corner in corners] blockRead = div(block(imgE, cs), pow(blockSide, 2)) # the op # a RandomAccessibleInterval view of the op, computed with shorts but seen as bytes view = blockRead.view(UnsignedShortType(), UnsignedByteType()) # Views.subsample by 2 will turn a 512-pixel width to a 257 width, # so crop to proper interval 256 level = Views.interval( Views.subsample(view, blockSide), [0] * img.numDimensions(), # min [ img.dimension(d) / blockSide - 1 for d in xrange(img.numDimensions()) ]) # max pyramid.append(level) """ for i, level in enumerate(pyramid): imp_level = IL.wrap(level, str(i+1)) imp_level.show() win = imp.getWindow().getCanvas().
from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.img.array import ArrayImg from net.imglib2.img.basictypeaccess import ByteAccess from net.imglib2.type.numeric.integer import UnsignedByteType from math import sin, cos, pi # Example 1: a virtual blank image. No pixel array backing. t = UnsignedByteType() img = ArrayImg( type('ConstantValue', (ByteAccess, ), { 'getValue': lambda self, index: 255 })(), [512, 512], t.getEntitiesPerPixel()) img.setLinkedType(t.getNativeTypeFactory().createLinkedType(img)) #IL.wrap(img, "white").show() # Example 1b: a virtual blank image, with the ByteAccess unpacked into a class class ConstantValue(ByteAccess): def __init__(self, value): self.value = value def getValue(self, index): return self.value def setValue(self, index, value): pass t = UnsignedByteType() data = ConstantValue(255)
from net.imglib2.view import Views from net.imglib2.util import Intervals from net.imglib2.view import IterableRandomAccessibleInterval from net.imagej.ops.stats import IterableMax from net.imglib2.algorithm.neighborhood import RectangleShape try: os.unlink(output_path) except OSError: pass input = scifio.datasetIO().open(input_path) ui.show(input) # add constant input = ops.math().add(input, UnsignedByteType(100)) ui.show(input) # normalization normalized = ops.create().img(input) ops.image().normalize(normalized, input) ui.show(normalized) # convolution kernel = ops.run("create.img", [3, 3], FloatType()) for p in kernel: p.set(1.0 / kernel.size()) convoluted = ops.create().img(normalized) ops.filter().convolve(convoluted, Views.extendMirrorSingle(normalized), kernel) ui.show(convoluted)
#@ DatasetService ds """ ops threshold types here: https://github.com/imagej/imagej-ops/tree/master/src/main/java/net/imagej/ops/threshold """ # Apply an automatic threshold from a given method. The threshold value 'threshold_value' # can be modulated by a relative parameter called 'relative_threshold' (if equal to 1 it does # not modify 'threshold_value') from net.imglib2.type.numeric.integer import UnsignedByteType # Get the histogram histo = ops.run("image.histogram", data) # Get the threshold threshold_value = ops.run("threshold.%s" % method_threshold, histo) # Modulate 'threshold_value' by 'relative_threshold' threshold_value = int(round(threshold_value.get() * relative_threshold)) # We should not have to do that... threshold_value = UnsignedByteType(threshold_value) # Apply the threshold thresholded = ops.run("threshold.apply", data, threshold_value) # Create output Dataset output = ds.create(thresholded)
#@ OpService ops #@ SCIFIO scifio #@ String input_path #@ String output_path #@ UIService ui #@ DatasetService datasets import os from net.imglib2.type.numeric.integer import UnsignedByteType from net.imglib2.type.logic import BitType from net.imglib2.view import Views try: os.unlink(output_path) except OSError: pass input = scifio.datasetIO().open(input_path) output = ops.create().img(input, BitType()) threshold = UnsignedByteType(128) ops.threshold().apply(output, input, threshold) output8bit = ops.convert().uint8(output) output8bit = ops.math().multiply(output8bit, UnsignedByteType(255)) scifio.datasetIO().save(datasets.create(output8bit), output_path) ui.show(output8bit) print("OK")