def combine(op, title, *ops): edges_img = img.factory().imgFactory(FloatType()).create(img) compute(op(*ops)).into(edges_img) imp = IL.wrap(edges_img, title) imp.getProcessor().resetMinAndMax() imp.show() return imp
def findPeaks(img4D, params): """ img4D: a 4D RandomAccessibleInterval params["frames"]: the number of consecutive time points to average towards detecting peaks with difference of Gaussian. Returns a list of lists of peaks found, one list per time point. """ frames = params["frames"] # Work image: the current sum sum3D = ArrayImgs.unsignedLongs([img4D.dimension(d) for d in [0, 1, 2]]) peaks = [] # Sum of the first set of frames compute(add([Views.hyperSlice(img4D, 3, i) for i in xrange(frames)])).into(sum3D) # Extract nuclei from first sum3D peaks.append(doGPeaks(sum3D, params)) # Running sums: subtract the first and add the last for i in xrange(frames, img4D.dimension(3), 1): compute(add(sub(sum3D, Views.hyperSlice(img4D, 3, i - frames)), Views.hyperSlice(img4D, 3, i))) \ .into(sum3D) # Extract nuclei from sum4D peaks.append(doGPeaks(sum3D, params)) return peaks
def populateInstances(instances, synth_imgs, class_index, mins, maxs): # Populate the training data: create the filter bank for each feature image # by reading values from the interval defined by mins and maxs target = ArrayImgs.floats([width, height]) interval = FinalInterval(mins, maxs) n_samples = Intervals.numElements(interval) for img in synth_imgs: vectors = [zeros(len(attributes), 'd') for _ in xrange(n_samples)] for k, op in enumerate(filterBank(img, sumType=DoubleType())): imgOp = compute(op).into(target) for i, v in enumerate(Views.interval(imgOp, interval)): vectors[i][k] = v.getRealDouble() for vector in vectors: vector[-1] = class_index instances.add(DenseInstance(1.0, vector))
def projectLastDimension(img, showEarly=False): """ Project the last dimension, e.g. a 4D image becomes a 3D image, using the provided reducing function (e.g. min, max, sum). """ last_dimension = img.numDimensions() - 1 # The collapsed image imgC = ArrayImgs.unsignedShorts( [img.dimension(d) for d in xrange(last_dimension)]) if showEarly: showStack( imgC, title="projected") # show it early, will be updated progressively if img.dimension(last_dimension) > 10: # one by one print "One by one" for i in xrange(img.dimension(last_dimension)): print i compute(maximum(imgC, Views.hyperSlice(img, last_dimension, i))).into(imgC) else: # Each sample of img3DV is a virtual vector over all time frames at that 3D coordinate: imgV = Views.collapseReal(img) # Reduce each vector to a single scalar, using a Converter # The Converter class reduce_max = makeCompositeToRealConverter( reducer_class=Math, reducer_method="max", reducer_method_signature="(DD)D") img3DC = convert(imgV, reduce_max.newInstance(), img.randomAccess().get().getClass()) ImgUtil.copy(ImgView.wrap(imgV, img.factory()), imgC) return imgC
def classify(img, classifier, class_names, ops=None, distribution_class_index=-1): """ img: a 2D RandomAccessibleInterval. classifier: a WEKA Classifier instance, like SMO or FastRandomForest, etc. Any. If it's a string, interprets it as a file path and attempts to deserialize a previously saved trained classifier. class_names: the list of names of each class to learn. ops: the filter bank of ImgMath ops for the img. distribution_class_index: defaults to -1, meaning return the class index for each pixel. When larger than -1, it's interpreted as a class index, and returns instead the floating-point value of each pixel in the distribution of that particular class index. """ if type(classifier) == str: classifier = SerializationHelper.read(classifier) ops = ops if ops else filterBank(img) attributes = ArrayList() for i in xrange(len(ops)): attributes.add(Attribute("attr-%i" % i)) #for name in classifier.attributeNames()[0][1]: # attributes.add(Attribute(name)) attributes.add(Attribute("class", class_names)) info = Instances("structure", attributes, 1) info.setClassIndex(len(attributes) -1) opImgs = [compute(op).into(ArrayImgs.floats([img.dimension(0), img.dimension(1)])) for op in ops] cs_opImgs = Views.collapse(Views.stack(opImgs)) result = ArrayImgs.floats([img.dimension(0), img.dimension(1)]) cr = result.cursor() cop = Views.iterable(cs_opImgs).cursor() while cr.hasNext(): tc = cop.next() vector = array((tc.get(i).getRealDouble() for i in xrange(len(opImgs))), 'd') vector += array([0], 'd') di = DenseInstance(1.0, vector) di.setDataset(info) # the list of attributes if distribution_class_index > -1: cr.next().setReal(classifier.distributionForInstance(di)[distribution_class_index]) else: cr.next().setReal(classifier.classifyInstance(di)) return result
def filterBankRotations(img, angles=xrange(0, 46, 9), # sequence, in degrees filterBankFn=filterBank, # function that takes an img as sole positional argument outputType=FloatType()): """ img: a RandomAccessibleInterval. filterBankFn: the function from which to obtain a sequence of ImgMath ops. angles: a sequence of angles in degrees. outputType: for materializing rotated operations and rotating them back. For every angle, will prepare a rotated view of the image, then create a list of ops on the basis of that rotated view, then materialize each op into an image so that an unrotated view can be returned back. returns a list of unrotated views, each containing the values of applying each op to the rotated view. """ ops_rotations = [] for angle in angles: imgRot = img if 0 == angle else rotatedView(img, angle) ops = filterBankFn(imgRot) # Materialize these two combination ops and rotate them back (rather, a rotated view) interval = Intervals.translate(img, [(imgRot.dimension(d) - img.dimension(d)) / 2 for d in xrange(img.numDimensions())]) for op in ops: imgOpRot = compute(op).intoArrayImg(outputType) if 0 == angle: ops_rotations.append(imgOpRot) continue # Rotate them back and crop view imgOpUnrot = rotatedView(imgOpRot, -angle, enlarge=False) imgOp = Views.zeroMin(Views.interval(imgOpUnrot, interval)) #if angle == 0 or angle == 45: # IL.wrap(imgOpRot, "imgOpRot angle=%i" % angle).show() # IL.wrap(imgOpUnrot, "imgOpUnrot angle=%i" % angle).show() # IL.wrap(imgOp, "imgOp angle=%i" % angle).show() ops_rotations.append(imgOp) return ops_rotations
def filterBankBlockStatistics(img, block_width=5, block_height=5, integralImgE=None, sumType=UnsignedLongType(), converter=Util.genericRealTypeConverter()): # corners of a block centered at the pixel block_width = int(block_width) block_height = int(block_height) w0 = -block_width/2 # e.g. -2 when block_width == 4 and also when block_width == 5 h0 = -block_height/2 decX = 1 if 0 == block_width % 2 else 0 decY = 1 if 0 == block_height % 2 else 0 w1 = block_width/2 - decX # e.g. 2 when block_width == 5 but 1 when block_width == 4 h1 = block_height/2 - decY corners = [[w0, h0], [w1, h0], [w0, h1], [w1, h1]] # Create the integral image, stored as 64-bit if not integralImgE: alg = IntegralImg(img, sumType, converter) alg.process() integralImgE = Views.extendBorder(alg.getResult()) # Create the integral image of squares, stored as 64-bit sqimg = compute(power(img, 2)).view(sumType) algSq = IntegralImg(sqimg, sumType, converter) algSq.process() integralImgSqE = Views.extendBorder(algSq.getResult()) # block mean: creates holes in blurred membranes opMean = div(block(integralImgSqE, corners), block_width * block_height) # block variance: sum of squares minus square of sum opVariance = sub(block(integralImgSqE, corners), power(block(integralImgE, corners), 2)) opVarianceNonZero = let("var", opVariance, IF(LT("var", 0), THEN(0), ELSE("var"))) return [opMean, opVarianceNonZero]
def createTrainingData(img, samples, class_names, n_samples=0, ops=None): """ img: a 2D RandomAccessibleInterval. samples: a sequence of long[] (or int numeric sequence or Localizable) and class_index pairs; can be a generator. n_samples: optional, the number of samples (in case samples is e.g. a generator). class_names: a list of class names, as many as different class_index. ops: optional, the sequence of ImgMath ops to apply to the img, defaults to filterBank(img) return an instance of WEKA Instances """ ops = ops if ops else filterBank(img) if 0 == n_samples: n_samples = len(samples) # Define a WEKA Attribute for each feature (one for op in the filter bank, plus the class) attribute_names = ["attr-%i" % (i+1) for i in xrange(len(ops))] attributes = ArrayList() for name in attribute_names: attributes.add(Attribute(name)) # Add an attribute at the end for the classification classes attributes.add(Attribute("class", class_names)) # Create the training data structure training_data = Instances("training", attributes, n_samples) training_data.setClassIndex(len(attributes) -1) opImgs = [compute(op).into(ArrayImgs.floats([img.dimension(0), img.dimension(1)])) for op in ops] ra = Views.collapse(Views.stack(opImgs)).randomAccess() for position, class_index in samples: ra.setPosition(position) tc = ra.get() vector = array((tc.get(i).getRealDouble() for i in xrange(len(opImgs))), 'd') vector += array([class_index], 'd') training_data.add(DenseInstance(1.0, vector)) return training_data
int_converter = Util.genericIntegerTypeConverter() # Create the integral image of an 8-bit input, stored as 64-bit alg = IntegralImg(img, UnsignedLongType(), int_converter) alg.process() integralImg = alg.getResult() # Read out blocks of radius 5 (i.e. 10x10 for a 2d image) # in a way that is entirely n-dimensional (applies to 1d, 2d, 3d, 4d ...) radius = 5 nd = img.numDimensions() op = div(block(Views.extendBorder(integralImg), [radius] * nd), pow(radius * 2, nd)) blurred = img.factory().create(img) # an 8-bit image # Compute in floats, store result into longs # using a default generic RealType converter via t.setReal(t.getRealDouble()) compute(op).into(blurred, None, FloatType(), None) # Show the blurred image with the same LUT as the original imp2 = IL.wrap(blurred, "integral image radius 5 blur") imp2.getProcessor().setLut(imp.getProcessor().getLut()) imp2.show() # Compare with Gaussian blur from ij import ImagePlus from ij.plugin.filter import GaussianBlur from ij.gui import Line, ProfilePlot # Gaussian of the original image imp_gauss = ImagePlus(imp.getTitle() + " Gauss", imp.getProcessor().duplicate()) GaussianBlur().blurGaussian(imp_gauss.getProcessor(), radius)
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) IL.wrap(max_rgb, "max RGB").show()
ra.read(bytes) return ArrayImgs.unsignedBytes(bytes, [width, height, depth]) finally: ra.close() bird = readBinaryMaskImg(os.path.join(baseDir, "birdsIm/b21.im"), 128, 128, 128, 1024) airplane = readBinaryMaskImg(os.path.join(baseDir, "airplanesIm/b14.im"), 128, 128, 128, 1024) # Rotate bird: starts with posterior view, dorsal down # Rotate 180 degrees around Y axis birdY90 = Views.rotate(bird, 2, 0) # 90 birdY180 = Views.rotate(birdY90, 2, 0) # 90 again: 180 # Copy rotated bird into ArrayImg dims = Intervals.dimensionsAsLongArray(birdY90) img1 = compute(ImgSource(birdY180)).into(ArrayImgs.unsignedBytes(dims)) # Rotate airplane: starts with dorsal view, anterior down # Set to: coronal view, but dorsal is still down airplaneC = Views.rotate(airplane, 2, 1) # Set to dorsal up: rotate 180 degrees airplaneC90 = Views.rotate(airplaneC, 0, 1) # 90 airplaneC180 = Views.rotate(airplaneC90, 0, 1) # 90 again: 180 # Copy rotated airplace into ArrayImg img2 = compute(ImgSource(airplaneC180)).into(ArrayImgs.unsignedBytes(dims)) # Find edges def findEdgePixels(img): edge_pix = []
def mergeMax(img1, img2, imgT): return compute(maximum(img1, img2)).into(imgT)
def maxProjectLastDimension(img, strategy="1by1", chunk_size=0): last_dimension = img.numDimensions() -1 if "1by1" == strategy: exe = newFixedThreadPool() try: n_threads = exe.getCorePoolSize() imgTs = [ArrayImgs.unsignedShorts(list(Intervals.dimensionsAsLongArray(img))[:-1]) for i in xrange(n_threads)] def mergeMax(img1, img2, imgT): return compute(maximum(img1, img2)).into(imgT) def hyperSlice(index): return Views.hyperSlice(img, last_dimension, index) # The first n_threads mergeMax: futures = [exe.submit(Task(mergeMax, hyperSlice(i*2), hyperSlice(i*2 +1), imgTs[i])) for i in xrange(n_threads)] # As soon as one finishes, merge it with the next available hyperSlice next = n_threads while len(futures) > 0: # i.e. not empty imgT = futures.pop(0).get() if next < img.dimension(last_dimension): futures.append(exe.submit(Task(mergeMax, imgT, hyperSlice(next), imgT))) next += 1 else: # Run out of hyperSlices to merge if 0 == len(futures): return imgT # done # Merge imgT to each other until none remain futures.append(exe.submit(Task(mergeMax, imgT, futures.pop(0).get(), imgT))) finally: exe.shutdownNow() else: # By chunks imglibtype = img.randomAccess().get().getClass() # The Converter class reduce_max = makeCompositeToRealConverter(reducer_class=Math, reducer_method="max", reducer_method_signature="(DD)D") if chunk_size > 0: # map reduce approach exe = newFixedThreadPool() try: def projectMax(img, minC, maxC, reduce_max): imgA = ArrayImgs.unsignedSorts(Intervals.dimensionsAsLongArray(imgC)) ImgUtil.copy(ImgView.wrap(convert(Views.collapseReal(Views.interval(img, minC, maxC)), reduce_max.newInstance(), imglibtype), img.factory()), imgA) return imgA # The min and max coordinates of all dimensions except the last one minCS = [0 for d in xrange(last_dimension)] maxCS = [img.dimension(d) -1 for d in xrange(last_dimension)] # Process every chunk in parallel futures = [exe.submit(Task(projectMax, img, minCS + [offset], maxCS + [min(offset + chunk_size, img.dimension(last_dimension)) -1])) for offset in xrange(0, img.dimension(last_dimension), chunk_size)] return reduce(lambda f1, f2: compute(maximum(f1.get(), f2.get())).into(f1.get(), futures)) finally: exe.shutdownNow() else: # One chunk: all at once # Each sample of img3DV is a virtual vector over all time frames at that 3D coordinate # Reduce each vector to a single scalar, using a Converter img3DC = convert(Views.collapseReal(img), reduce_max.newInstance(), imglibtype) imgA = ArrayImgs.unsignedShorts([img.dimension(d) for d in xrange(last_dimension)]) ImgUtil.copy(ImgView.wrap(imgV, img.factory()), imgA) return imgA
imp = IL.wrap(edges_img, title) imp.getProcessor().resetMinAndMax() imp.show() return imp imp_max = combine(maximum, "max edges", opTop, opBottom, opLeft, opRight) imp_min = combine(minimum, "min edges", opTop, opBottom, opLeft, opRight) # Create a mask for blobs that don't contact the edges of the image imp_mask = ImagePlus("blobs mask", imp_max.getProcessor()) IJ.run(imp_mask, "Convert to Mask", "") # result has inverted LUT IJ.run(imp_mask, "Fill Holes", "") IJ.run(imp_mask, "Invert LUT", "") # revert to non-inverted LUT imp_mask.show() """ edges1 = minimum(opTop, opBottom, opLeft, opRight) edges2 = maximum(opTop, opBottom, opLeft, opRight) min_edges = img.factory().imgFactory(FloatType()).create(img) compute(edges1).into(min_edges) imp_min = IL.wrap(min_edges, "edges min") imp_min.getProcessor().resetMinAndMax() imp_min.show() max_edges = min_edges.factory().create(img) compute(edges2).into(max_edges) imp_max = IL.wrap(max_edges, "edges max") imp_max.getProcessor().resetMinAndMax() imp_max.show() """
# 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() # Compute now the image color saturation saturation = ArrayImgFactory(FloatType()).create(img) compute( let( "red", red, # store as directly readable variables (no dictionary lookups) "green", green, # so that only 3 cursors are needed instead of 6 "blue", blue,
b = ArrayImgs.floats(bb, [width, height]) #print "ArrayImg:", b.iterationOrder() ImgUtil.copy(ImgView.wrap(hue.view(FloatType()), None), h) ImgUtil.copy(ImgView.wrap(saturation.view(FloatType()), None), s) ImgUtil.copy(ImgView.wrap(brightness.view(FloatType()), None), b) stack = ImageStack(width, height) stack.addSlice(FloatProcessor(width, height, hb, None)) stack.addSlice(FloatProcessor(width, height, sb, None)) stack.addSlice(FloatProcessor(width, height, bb, None)) imp = ImagePlus("hsb", stack) return imp # For the test, transfer converted views into arrays ared = compute(img(red)).into( ArrayImgs.unsignedBytes([rgb.dimension(0), rgb.dimension(1)])) agreen = compute(img(green)).into( ArrayImgs.unsignedBytes([rgb.dimension(0), rgb.dimension(1)])) ablue = compute(img(blue)).into( ArrayImgs.unsignedBytes([rgb.dimension(0), rgb.dimension(1)])) def timeit(fn, *args, **kwargs): n_iterations = 20 times = [] for i in xrange(n_iterations): t0 = System.nanoTime() imp = fn(*args, **kwargs)
from net.imglib2.algorithm.math.ImgMath import compute, block, div, offset, add from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.img.array import ArrayImgs from net.imglib2.type.numeric.real import FloatType from net.imglib2.view import Views from net.imglib2.util import Intervals from ij import IJ imp = IJ.getImage() # an 8-bit image img = IL.wrap(imp) # Create the integral image of an 8-bit input, stored as 64-bit target = ArrayImgs.unsignedLongs(Intervals.dimensionsAsLongArray(img)) # Copy input onto the target image compute(img).into(target) # Extend target with zeros, so that we can read at coordinate -1 imgE = Views.extendZero(target) # Integrate every dimension, cummulatively by writing into # a target image that is also the input for d in xrange(img.numDimensions()): coord = [0] * img.numDimensions() # array of zeros coord[d] = -1 # Cummulative sum along the current dimension # Note that instead of the ImgMath offset op, # we could have used Views.translate(Views.extendZero(target), [1, 0])) # (Notice though the sign change in the translation) integral = add(target, offset(imgE, coord)) compute(integral).into(target) # The target is the integral image integralImg = target
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()
from net.imglib2.algorithm.math.ImgMath import compute, block, div, offset, add from net.imglib2.algorithm.math.abstractions import Util from net.imglib2.algorithm.integral import IntegralImg from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.type.numeric.integer import UnsignedByteType, \ UnsignedShortType, UnsignedLongType from net.imglib2.view import Views from ij import IJ imp = IJ.getImage() # e.g. EM of Drosophila neurons 180-220-sub512x512-30.tif #imp = IJ.openImage("/home/albert/lab/TEM/abd/microvolumes/Seg/180-220-sub/180-220-sub512x512-30.tif") img = compute(IL.wrap(imp)).intoImg(UnsignedShortType()) # in 16-bit # Create an integral image in longs alg = IntegralImg(img, UnsignedLongType(), Util.genericIntegerTypeConverter()) alg.process() integralImg = alg.getResult() # Create an image pyramid as views, with ImgMath and imglib2, # which amounts to scale area averaging sped up by the integral image # and generated on demand whenever each pyramid level is read. 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
from net.imglib2.type.numeric.real import FloatType ft = FloatType(10) ft.pow(2) print ft from net.imglib2.algorithm.math.ImgMath import compute, add, power from net.imglib2.img.array import ArrayImgs from net.imglib2.img.display.imagej import ImageJFunctions as IL img = ArrayImgs.floats([10, 10, 10]) compute(add(img, 5)).into(img) # in place compute(power(img, 2)).into(img) # in place print 25 * 10 * 10 * 10 == sum(t.get() for t in img.cursor()) IL.wrap(img, "5 squared").show()
LoopBuilder.setImages(red, green, img_sub).forEachPixel(Consumer(threshold)) IL.wrap(img_sub, "LoopBuilder").show() # Takes 10 seconds!! An eternity compared to the other two fast methods # Example 3: with Imglib2 ImgMath from net.imglib2.algorithm.math.ImgMath import compute, IF, THEN, ELSE, greaterThan from net.imglib2.algorithm.math.abstractions import Util from net.imglib2.converter import Converters from net.imglib2.img.array import ArrayImgs from net.imglib2.util import Intervals from net.imglib2.img.display.imagej import ImageJFunctions as IL 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 operation = IF(greaterThan(red, threshold -1), THEN(green), ELSE(0)) print Util.hierarchy(operation) IL.wrap(operation.view(), "ImgMath view").show() img_sub = compute(operation).into(ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img))) IL.wrap(img_sub, "ImgMath img").show()
img1 = intoImg(pixels1) img2 = intoImg(pixels2) img3 = intoImg(pixels3) img4 = intoImg(pixels4) def same(img1, img2): c1 = img1.cursor() c2 = img2.cursor() while c1.hasNext(): if c1.next().get() != c2.next().get(): return False return True imgAND = compute(AND(img1, img2)).intoArrayImg() #IL.wrap(img, "AND").show() print "AND:", same(img1, imgAND) imgOR = compute(OR(img1, img2)).intoArrayImg() print "OR:", same(img2, imgOR) imgXOR = compute(XOR(img1, img2)).intoArrayImg() print "XOR:", same(img3, imgXOR) imgNOT = compute(NOT(img1)).intoArrayImg() print "NOT:", same(img4, imgNOT) # Test LogicalAndBoolean imgIFAND = compute(IF(AND(LT(img1, 1), LT(img2, 1)), THEN(1), ELSE(0))).intoArrayImg()
# 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(max([red, green, blue]), 255.0)).into(brightness) # Show the brightness image impB = IL.wrap(brightness, imp.getTitle() + " brightness") impB.show() # Compute now the image color saturation saturation = ArrayImgFactory(FloatType()).create(img) compute( let( "red", red, "green", green, "blue", blue, "max", maximum([var("red"), var("green"), var("blue")]), "min", minimum([var("red"), var("green"), var("blue")]), IF(EQ(0, var("max")), THEN(0),
populateInstances(training_data, synth_imgs_mit_boundary, 1, [15, 15], [16, 16]) # Populate the training data for class "other" from two images # entirely filled with background or foreground plus noise target = ArrayImgs.floats([width, height]) interval = FinalInterval([14, 14], [17, 17]) n_samples = Intervals.numElements(interval) for ci, v in enumerate([fillValue, backgroundValue]): for _ in xrange(training_data.size() / 4): # the other 2/4 are the membrane and mit boundary other = syntheticEM([], width, height, 0, v, noise=True) vectors = [zeros(len(attributes), 'd') for _ in xrange(n_samples)] for k, op in enumerate(filterBank(IL.wrap(other), sumType=DoubleType())): imgOp = compute(op).into(target) for i, v in enumerate(Views.interval(imgOp, interval)): vectors[i][k] = v.getRealDouble() for vector in vectors: vector[-1] = ci + 2 # class index training_data.add(DenseInstance(1.0, vector)) # Create a classifier: support vector machine (SVM, an SMO in WEKA) classifier = SMO() classifier.buildClassifier(training_data) print classifier.toString() # Save the trained classifier for later SerializationHelper.write("/tmp/svm-em-mem-mit", classifier) """ imp = WindowManager.getImage("180-220-sub512x512-30.tif") # IJ.getImage() # e.g. 8-bit EM of Drosophila neurons 180-220-sub512x512-30.tif