def testJython(imgred, imggreen, imgblue): width, height = rgb.dimension(0), rgb.dimension(1) hb = zeros(width * height, 'f') sb = zeros(width * height, 'f') bb = zeros(width * height, 'f') cred = imgred.cursor() cgreen = imggreen.cursor() cblue = imgblue.cursor() i = 0 while cred.hasNext(): r = cred.next().getRealFloat() g = cgreen.next().getRealFloat() b = cblue.next().getRealFloat() cmax = max(r, g, b) cmin = min(r, g, b) bb[i] = cmax / 255.0 if 0 != cmax: sb[i] = (cmax - cmin) / cmax # Else leave sb[i] at zero if 0 == sb[i]: h = 0 else: span = cmax - cmin redc = (cmax - r) / span greenc = (cmax - g) / span bluec = (cmax - b) / span if r == cmax: h = bluec - greenc elif g == cmax: h = 2.0 + redc - bluec else: h = 4.0 + greenc - redc h /= 6.0 if h < 0: h += 1.0 hb[i] = h i += 1 hh = ArrayImgs.floats(hb, [width, height]) ss = ArrayImgs.floats(sb, [width, height]) bb = ArrayImgs.floats(bb, [width, height]) return Views.stack(hh, ss, bb)
def loadUnsignedShort(filepath, invert=True, CLAHE_params=None): """ Returns an ImgLib2 ArrayImg """ imp = loadImp(filepath) if invert: imp.getProcessor().invert() if CLAHE_params is not None: blockRadius, n_bins, slope = CLAHE_params CLAHE.run(imp, blockRadius, n_bins, slope, None) return ArrayImgs.unsignedShorts( imp.getProcessor().getPixels(), [imp.getWidth(), imp.getHeight()])
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
def readUnsignedBytes(path, dimensions, header=0): """ Read a file as an ArrayImg of UnsignedShortType """ ra = RandomAccessFile(path, 'r') try: if header < 0: # Interpret from the end: useful for files with variable header lengths # such as some types of uncompressed TIFF formats header = ra.length() + header ra.skipBytes(header) bytes = zeros(reduce(operator.mul, dimensions), 'b') ra.read(bytes) return ArrayImgs.unsignedBytes(bytes, dimensions) finally: ra.close()
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 readFIBSEMdat(path, channel_index=-1, header=1024, magic_number=3555587570): """ Read a file from Shan Xu's FIBSEM software, where two channels are interleaved. Assumes channels are stored in 16-bit. path: the file path to the .dat file. channel_index: the 0-based index of the channel to parse, or -1 (default) for all. header: defaults to a length of 1024 bytes magic_number: defaults to that for version 8 of Shan Xu's .dat image file format. """ ra = RandomAccessFile(path, 'r') try: # Check the magic number ra.seek(0) if ra.readInt() & 0xffffffff != magic_number: print "Magic number mismatch" return None # Read the number of channels ra.seek(32) numChannels = ra.readByte() & 0xff # a single byte as unsigned integer # Parse width and height ra.seek(100) width = ra.readInt() ra.seek(104) height = ra.readInt() print numChannels, width, height # Read the whole interleaved pixel array ra.seek(header) bytes = zeros(width * height * 2 * numChannels, 'b') # 2 for 16-bit ra.read(bytes) print "read", len(bytes), "bytes" # takes ~2 seconds # Parse as 16-bit array sb = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asShortBuffer() shorts = zeros(width * height * numChannels, 'h') sb.get(shorts) # Deinterleave channels # With Weaver: fast channels = w.deinterleave(shorts, numChannels, channel_index) # With python array sampling: very slow, and not just from iterating whole array once per channel # seq = xrange(numChannels) if -1 == channel_index else [channel_index] #channels = [shorts[i::numChannels] for i in seq] # With clojure: extremely slow, may be using reflection unexpectedly #channels = deinterleave.invoke(shorts, numChannels) print len(channels) # Shockingly, these values are signed shorts, not unsigned! return [ArrayImgs.shorts(s, [width, height]) for s in channels] finally: ra.close()
def readFloats(path, dimensions, header=0, byte_order=ByteOrder.LITTLE_ENDIAN): """ Read a file as an ArrayImg of FloatType """ size = reduce(operator.mul, dimensions) ra = RandomAccessFile(path, 'r') try: if header < 0: # Interpret from the end: useful for files with variable header lengths # such as some types of uncompressed TIFF formats header = ra.length() + header ra.skipBytes(header) bytes = zeros(size * 4, 'b') ra.read(bytes) floats = zeros(size, 'f') ByteBuffer.wrap(bytes).order(byte_order).asFloatBuffer().get(floats) return ArrayImgs.floats(floats, dimensions) finally: ra.close()
def readUnsignedShorts(path, dimensions, header=0, return_array=False, byte_order=ByteOrder.LITTLE_ENDIAN): """ Read a file as an ArrayImg of UnsignedShortType """ size = reduce(operator.mul, dimensions) ra = RandomAccessFile(path, 'r') try: if header < 0: # Interpret from the end: useful for files with variable header lengths # such as some types of uncompressed TIFF formats header = ra.length() + header ra.skipBytes(header) bytes = zeros(size * 2, 'b') ra.read(bytes) shorts = zeros(size, 'h') # h is for short ByteBuffer.wrap(bytes).order(byte_order).asShortBuffer().get(shorts) return shorts if return_array else ArrayImgs.unsignedShorts(shorts, dimensions) finally: ra.close()
def prepare(index): # Prepare the img for deconvolution: # 0. Transform in one step. # 1. Ensure its pixel values conform to expectations (no zeros inside) # 2. Copy it into an ArrayImg for faster recurrent retrieval of same pixels syncPrint("Preparing %s CM0%i for deconvolution" % (tm_dirname, index)) img = klb_loader.get(filepaths[index]) # of UnsignedShortType imgP = prepareImgForDeconvolution( img, transforms[index], target_interval) # returns of FloatType # Copy transformed view into ArrayImg for best performance in deconvolution imgA = ArrayImgs.floats(Intervals.dimensionsAsLongArray(imgP)) #ImgUtil.copy(ImgView.wrap(imgP, imgA.factory()), imgA) ImgUtil.copy(imgP, imgA, n_threads / 2) # parallel copying syncPrint("--Completed preparing %s CM0%i for deconvolution" % (tm_dirname, index)) imgP = None img = None return (index, imgA)
def makeInterpolatedImage(img1, search1, img2, search2, weight): """ weight: float between 0 and 1 """ img3 = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img1)) c1 = img1.cursor() c2 = img2.cursor() c3 = img3.cursor() while c3.hasNext(): t1 = c1.next() t2 = c2.next() t3 = c3.next() sign1 = -1 if 0 == t1.get() else 1 sign2 = -1 if 0 == t2.get() else 1 search1.search(c1) search2.search(c2) value1 = sign1 * search1.getDistance() * (1 - weight) value2 = sign2 * search2.getDistance() * weight if value1 + value2 > 0: t3.setOne() return img3
def oneStep(index=0): # Combining transforms into one, via a translation to account of the ROI crop img = klb.readFull(filepaths[index]) # klb_loader.get(filepaths[index]) t1 = cmIsotropicTransforms[index] t2 = affine3D( [1, 0, 0, -roi[0][0], 0, 1, 0, -roi[0][1], 0, 0, 1, -roi[0][2]]) t3 = affine3D(fineTransformsPostROICrop[index]).inverse() aff = AffineTransform3D() aff.set(t1) aff.preConcatenate(t2) aff.preConcatenate(t3) # Final interval is now rooted at 0,0,0 given that the transform includes the translation imgP = prepareImgForDeconvolution( img, aff, FinalInterval([0, 0, 0], [maxC - minC for minC, maxC in izip(roi[0], roi[1])])) # Copy transformed view into ArrayImg for best performance in deconvolution imgA = ArrayImgs.floats(Intervals.dimensionsAsLongArray(imgP)) ImgUtil.copy(ImgView.wrap(imgP, imgA.factory()), imgA) IL.wrap(imgA, "one step index %i" % index).show()
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
def getPixels(self, n): # 'n' is 1-based # Target 2D array img to copy data into aimg = ArrayImgs.unsignedShorts(self.dimensions[0:2]) # The number of slices of the 3D volume of a single timepoint nZ = self.img4d.dimension(2) # The slice_index if there was a single channel slice_index = int((n - 1) / 2) # 0-based, of the whole 4D series local_slice_index = slice_index % nZ # 0-based, of the timepoint 3D volume timepoint_index = int(slice_index / nZ) # Z blocks if 1 == n % 2: # Odd slice index: image channel fixedT = Views.hyperSlice(self.img4d, 3, timepoint_index) fixedZ = Views.hyperSlice(fixedT, 2, local_slice_index) w.copy(fixedZ.cursor(), aimg.cursor()) else: # Even slice index: spheres channel sd = SpheresData(self.kdtrees[timepoint_index], radius, inside, outside) volume = Views.interval(Views.raster(sd), self.dimensions3d) plane = Views.hyperSlice(volume, 2, local_slice_index) w.copy(plane.cursor(), aimg.cursor()) # return aimg.update(None).getCurrentStorageArray()
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
from net.imglib2.img.array import ArrayImgs from net.imglib2.view import Views from net.imglib2.type.numeric.integer import UnsignedByteType img1 = ArrayImgs.unsignedBytes([10, 10, 10]) img2 = ArrayImgs.unsignedBytes([10, 10, 10]) stack = Views.stack([img1, img2]) for t in Views.iterable(stack): t.setReal(1) assert 1000 + 1000 == sum(t.get() for t in Views.iterable(stack))
def readKernel(path): if kernel_header is None: imp = IJ.openImage(path) return ArrayImgs.floats(imp.getProcessor().getPixels(), [imp.getWidth(), imp.getHeight(), imp.getNSlices()]) return readFloats(path, kernel_dimensions, kernel_header)
aimgs = [] first = klb.readFull(os.path.join(srcDir, filtered[0])) dimensions = Intervals.dimensionsAsLongArray(first) for i in xrange(n_threads): m = Max(dimensions, filtered[i * chunk_size:(i + 1) * chunk_size]) m.start() threads.append(m) # Await completion of all for m in threads: m.join() # Merge all results into a single maximum projection max_projection = computeInto(maximum([m.aimg for m in threads]), ArrayImgs.floats(dimensions)) max3D = writeZip(max_projection, max_projection_path, title="max projection") max3D.show() # Step 3: detect the nuclei and write their coordinates to a CSV file calibration = [0.40625, 0.40625, 2.5] somaDiameters = [4.0, 4.9, 5.7, 6.5] # 10, 12, 14, 16 px peak_map = {} for somaDiameter in somaDiameters: # Parameters for detecting nuclei with difference of Gaussian
def __init__(self, dimensions, filenames): super(Thread, self).__init__() self.filenames = filenames self.aimg = ArrayImgs.floats(dimensions) self.klb = KLB.newInstance()
c.fwd() c.localize(pos) print "Cursor:", pos, "::", c.get() # Test RandomAccess ra = iraf.randomAccess() c = iraf.cursor() while c.hasNext(): c.fwd() ra.setPosition(c) c.localize(pos) print "RandomAccess:", pos, "::", ra.get() # Test source img: should be untouched c = img.cursor() while c.hasNext(): print "source:", c.next() # Test interval view: the middle 2x2 square v = Views.interval(iraf, [1, 1], [2, 2]) IL.wrap(v, "+2 view").show() # An array from 0 to 15 a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] pixels = array(a, 'b') img = ArrayImgs.unsignedBytes(pixels, [4, 4]) test(add(img, 2).view()) test(add(img, 2).view(FloatType()))
make_sure_path_exists( bp ) weightsTracker = WeightsTrackerVisitor( bp, separator ) coordinateTracker.addVisitor( fitTracker ) if doRender: coordinateTracker.addVisitor( matrixTracker ) coordinateTracker.addVisitor( floorTracker ) coordinateTracker.addVisitor( multiplierTracker ) coordinateTracker.addVisitor( weightsTracker ) # ImageJFunctions.show( subStrip ) tf = StripToMatrix( wholeStrip.dimension(0) / 2 ) store = ArrayImgs.doubles( subStrip.dimension( 0 ), subStrip.dimension( 1 ) ) CopyFromIntervalToInterval.copyToRealType( subStrip, store ) matrix = Views.interval( TransformView( Views.extendValue( store, DoubleType( Double.NaN ) ), tf ), FinalInterval( [subStrip.dimension(1), subStrip.dimension(1)] ) ) # ImageJFunctions.show( matrix ) # ImageJFunctions.show( subStrip ) # ImageJFunctions.show( matrix ) print "adding thread for lower=%d and upper=%d" % (lower, upper) t = Thread( target = run, args = ( matrix, startingCoordinates, coordinateTracker, options ) ) t.start() threads.append( t ) for t in threads:
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])) clj = ClojureScriptEngine()
# 2022 I2K example # Albert Cardona 2022 # Create an ImgLib2 ArrayImg # 1. With ArrayImgs: trivial from net.imglib2.img.array import ArrayImgs img = ArrayImgs.unsignedShorts([512, 512]) # Or reusing the pixel array from e.g., an open ImageJ image: from net.imglib2.img.array import ArrayImgs from ij import IJ from ij.process import ShortProcessor imp = IJ.getImage() # most recently activated ImageJ image window ip = imp.getProcessor() if isinstance(ip, ShortProcessor): width, height = imp.getWidth(), imp.getHeight() pixelsU16 = ip.getPixels() img = ArrayImgs.unsignedShorts(pixelsU16, [width, height]) # Or creating a new pixel array from scratch from net.imglib2.img.array import ArrayImgs from jarray import zeros pixelsU16 = zeros(512 * 512, 'h') # 'h' means short[] img = ArrayImgs.unsignedShorts(pixelsU16, [512, 512]) # 2. With ArrayImgFactory: unnecessary, use ArrayImgs from net.imglib2.img.array import ArrayImgFactory from net.imglib2.type.numeric.integer import UnsignedShortType
# in the VIB's vib.BinaryInterpolator class, for ij.ImagePlus. # # # Note that a java-based implementation would be significantly faster. from net.imglib2.img.array import ArrayImgs from org.scijava.vecmath import Point3f from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.view import Views from net.imglib2.type.numeric.integer import UnsignedByteType from jarray import zeros from net.imglib2.algorithm.morphology.distance import DistanceTransform # First 3D mask: a sphere img1 = ArrayImgs.unsignedBytes([100, 100, 100]) p = zeros(3, 'l') cursor = img1.cursor() middle = Point3f(49.5,49.5, 49.5) distance_sq = float(30 * 30) while cursor.hasNext(): cursor.fwd() cursor.localize(p) if middle.distanceSquared(Point3f(p[0], p[1], p[2])) < distance_sq: cursor.get().setOne() else: cursor.get().setZero() imp1 = IL.wrap(img1, "sphere") imp1.setDisplayRange(0, 1)
# @OpService ops # @float[] arr # @long[] dims # @OUTPUT Img out from net.imagej.ops import Ops from net.imglib2.img import Img from net.imglib2.img.array import ArrayImgs arr = list(arr) dims = list(dims) out = ArrayImgs.floats(arr, dims)
from net.imglib2.img.array import ArrayImgs from time import time from itertools import imap from collections import deque from net.imglib2.util.Util import getTypeFromInterval from org.scijava.plugins.scripting.clojure import ClojureScriptEngine from net.imglib2.type.numeric.integer import UnsignedByteType from net.imglib2.type.operators import SetOne from java.util.function import Predicate, Consumer, Function from java.lang.invoke import MethodHandles, MethodType, LambdaMetafactory from java.lang import Void import sys from org.objectweb.asm import ClassWriter, Opcodes from java.lang import Object, ClassLoader, String, Class, Integer img = ArrayImgs.unsignedBytes([512, 512, 5]) n_iterations = 4 # Test 1: for loop for i in xrange(n_iterations): t0 = time() for t in img.cursor(): t.setOne() t1 = time() print "looping:", t1 - t0 # About 1 seconds # Test 2: imap + deque with maxlen=0 for i in xrange(n_iterations): t0 = time() # Performance almost as bad as the for loop
# Load the facc and cw classes loader = CustomClassLoader() accessClass = loader.defineClass("my/UnsignedByteToFloatAccess", facc.toByteArray()) samplerClass = loader.defineClass("my/UnsignedByteToFloatSamplerConverter", cw.toByteArray()) # Test SamplerConverter: from net.imglib2.img.array import ArrayImgs from net.imglib2.converter import Converters from net.imglib2.util import ImgUtil from net.imglib2.img import ImgView dimensions = [100, 100, 100] img1 = ArrayImgs.unsignedBytes(dimensions) c = img1.cursor() while c.hasNext(): c.next().setOne() img2 = ArrayImgs.floats(dimensions) def testASM(): ImgUtil.copy( ImgView.wrap( Converters.convertRandomAccessibleIterableInterval( img1, samplerClass.newInstance()), img1.factory()), img2) timeit(20, testASM)
imgB0, transformedView(imgB1, matrices["imgB0-imgB1"]), transformedView(imgB2, matrices["imgB0-imgB2"]), transformedView(imgB3, matrices["imgB0-imgB3"]) ] #viewInBDV(*transformed) viewAsStack(*transformed) exe = newFixedThreadPool(4) try: # Copy into ArrayImg def copyIntoArrayImg(img): return ImgMath.compute(ImgMath.img(img)).into(ArrayImgs.floats([img.dimension(d) for d in xrange(img.numDimensions())])) futures = [exe.submit(Task(copyIntoArrayImg, img)) for img in [imgB0, imgB1, imgB2, imgB3]] imgB0, imgB1, imgB2, imgB3 = [f.get() for f in futures] finally: exe.shutdown() viewAsStack(imgB0, imgB1, imgB2, imgB3) # ArrayImg instances # Read the kernel as a FloatType ArrayImg kernel = readFloats("/home/albert/lab/Raghav-IsoView-PSF/PSF-19x19x25.tif", [19, 19, 25], header=434) def affine3D(matrix): aff = AffineTransform3D() aff.set(*matrix) return aff
from net.imglib2.realtransform import RealViews, AffineTransform3D from net.imglib2.interpolation.randomaccess import NLinearInterpolatorFactory from net.imglib2.util import Intervals img = IL.wrap(IJ.getImage()) # Cut out a cube img1 = Views.zeroMin( Views.interval(img, [39, 49, 0], [39 + 378 - 1, 49 + 378 - 1, 378 - 1])) print[img1.dimension(d) for d in xrange(img1.numDimensions())] # Rotate the cube on the Y axis to the left img2 = Views.rotate(img1, 2, 0) # copy into ArrayImg img1a = ArrayImgs.unsignedShorts([378, 378, 378]) ImgMath.compute(ImgSource(img1)).into(img1a) img2a = ArrayImgs.unsignedShorts([378, 378, 378]) ImgMath.compute(ImgSource(img2)).into(img2a) img1 = img1a img2 = img2a IL.wrap(img1, "cube").show() IL.wrap(img2, "cube rotated").show() # Now register them # IMPORTANT PARAMETERS raw_calibration = [1.0, 1.0, 1.0] # micrometers per pixel
# @UIService ui import net.imglib2.img.array.ArrayImgs as ArrayImgs import bdv.util.BdvFunctions as BdvFunctions import random as random w = 101 h = w d = w img = ArrayImgs.unsignedBytes(w, h, d) img_ra = img.randomAccess() for x in range(0, w): for y in range(0, h): for z in range(0, d): img_ra.setPosition(x, 0) img_ra.setPosition(y, 1) img_ra.setPosition(z, 2) xo = x - 50 yo = y - 50 zo = z - 50 val = 255 - ( xo**2 + yo**2 + zo**2 ) ** 0.65 img_ra.get().setReal(int(val)) print('done')
from random import random from net.imglib2.algorithm.math import ImgMath from net.imglib2.util import ImgUtil from net.imglib2.img import ImgView import sys sys.path.append("/home/albert/lab/scripts/python/imagej/IsoView-GCaMP/") from lib.util import timeit roi = ( [1, 228, 0], # top-left coordinates [1 + 406 - 1, 228 + 465 - 1, 0 + 325 - 1]) # bottom-right coordinates (inclusive, hence the -1) dimensions = [maxC - minC + 1 for minC, maxC in zip(roi[0], roi[1])] imgU = ArrayImgs.unsignedShorts(dimensions) imgF = ArrayImgs.floats(dimensions) #c = imgF.cursor() #while c.hasNext(): # c.next().set(random() * 65535) ImgMath.compute(ImgMath.number(17)).into(imgF) ImgMath.compute(ImgMath.img(imgF)).into(imgU) aff = AffineTransform3D() """ aff.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0) """ aff.set(*[ 0.9999949529841275, -0.0031770224721305684, 2.3118912942710207e-05, -1.6032353998500826, 0.003177032139125933, 0.999994860398559,
from ij import IJ from net.imglib2.view import Views from net.imglib2.realtransform import AffineTransform3D, RealViews from net.imglib2.interpolation.randomaccess import NLinearInterpolatorFactory from net.imglib2.img.array import ArrayImgs from jarray import zeros from math import sqrt import sys sys.path.append("/home/albert/lab/scripts/python/imagej/IsoView-GCaMP") from lib.ui import showAsStack, makeTranslationUI from lib.util import affine3D # Create a [100,100,100] image with a sphere of radius 20 at the center aimg = ArrayImgs.unsignedBytes([10, 10, 10]) c = aimg.cursor() pos = zeros(3, 'l') while c.hasNext(): t = c.next() c.localize(pos) v = sqrt(sum(pow(p - 5, 2) for p in pos)) if v < 2: t.setReal(255) # Use the image to represent a channel # Transform each channel independently def identity(): return affine3D([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]) aff1 = identity()