def run(): # Ask for a folder containing all the time points, one per folder #dc = DirectoryChooser("Choose folder") #folder = dc.getDirectory() #folder = '/run/user/52828/gvfs/smb-share:server=keller-s7,share=microscopy1/SV3/RC_17-10-31/GCaMP6s_2_20171031_145624.corrected/SPM00' #folder = "/home/albert/shares/zlaticlab/Nadine/Raghav/2017-05-10/GCaMP6s_1_20170510_115003.corrected/dff_on_fused/from_Raghav/MVD_Results/" folder = "/home/albert/shares/zlaticlab/Nadine/Raghav/2017-05-10/GCaMP6s_1_20170510_115003.corrected/tests/dff_on_4view_fused/from_Raghav/MVD_Results/" print folder if not folder: return # Find the list of directories in that folder, and pick # one single file inside each, ending in: ending = "CM00_CHN00.klb" #DEBUGGING num_timepoints = 100 java = Weaver.method( """ static public final void maxer(final KLB klb, final ImgPlus target, final String path) throws java.io.IOException { Cursor c1 = target.cursor(); Cursor c2 = klb.readFull(path).cursor(); while (c1.hasNext()) { c1.next(); c2.next(); UnsignedShortType s1 = (UnsignedShortType) c1.get(); UnsignedShortType s2 = (UnsignedShortType) c2.get(); s1.set( (short) Math.max( s1.get(), s2.get() ) ); } } """, [KLB, ImgPlus, Cursor, UnsignedShortType]) max_img = None klb = KLB.newInstance() counter = 0 for root, dirs, files in os.walk(folder): for filename in files: if filename.endswith(ending): counter += 1 path = os.path.join(root, filename) print counter, path # Use the first opened stack as the image stack into which to accumulate max values if max_img is None: max_img = klb.readFull(path) else: java.maxer(klb, max_img, path) num_timepoints -= 1 if num_timepoints < 0: break # DONE IJF.show(max_img)
def run(): result = LoadParseQueryXML() result.addButton("Define a new dataset", Listener(result)) if not result.queryXML("XML Explorer", query, False, False, False, False): print "Cancelled dialog" return print "Resume" data = result.getData() xml = result.getXMLFileName() io = result.getIO() explorer = ViewSetupExplorer(data, xml, io) explorer.getFrame().toFront() # A handle into the data spimdata2 = explorer.getSpimData() # https://github.com/bigdataviewer/spimdata/blob/master/src/main/java/mpicbg/spim/data/registration/ViewRegistrations.java # A map of ViewId vs ViewRegistration (which extends ViewId, so likely are the same) # ViewId: https://github.com/bigdataviewer/spimdata/blob/master/src/main/java/mpicbg/spim/data/sequence/ViewId.java # ViewRegistration: https://github.com/bigdataviewer/spimdata/blob/master/src/main/java/mpicbg/spim/data/registration/ViewRegistration.java viewregs = spimdata2.getViewRegistrations().getViewRegistrations() #for k, v in viewregs.iteritems(): # print "timepointId:", k.getTimePointId(), "viewSetupId:", k.getViewSetupId(), "value: ", v # Shows that there are 4 views per timepoint: not fused! # And: each ViewRegistration holds only the transforms of each view of the timepoint, not the 3D pixels. # # https://github.com/bigdataviewer/spimdata/blob/master/src/main/java/mpicbg/spim/data/sequence/SequenceDescription.java seqdescr = spimdata2.getSequenceDescription() imgloader = seqdescr.getImgLoader() for view, viewreg in viewregs.iteritems(): # Each entry has its own TimePointId and ViewId viewID = view.getViewSetupId() timepointID = view.getTimePointId() # Instance of: org.janelia.simview.klb.bdv.KlbImgLoader$KlbSetupImgLoader loader = imgloader.getSetupImgLoader(viewID) # Dimensions instance dim = loader.getImageSize(timepointID) # VoxelDimensions instance voxelDim = loader.getVoxelSize(timepointID) # RandomAccessibleInterval instance rai = loader.getImage(timepointID, 0, [ImgLoaderHints.LOAD_COMPLETELY]) # The transforms transformList = viewreg.getTransformList() # TODO: register, the transform is in the viewreg IJF.show(rai) print map(dim.dimension, [0, 1, 2]) # [576L, 896L, 65L] print voxelDim.unit(), voxelDim.numDimensions(), map( voxelDim.dimension, [0, 1, 2]) # um 3 [1.0, 1.0, 1.0] break
# Albert Cardona 2022 from ij import IJ from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.view import Views from org.scijava.plugins.scripteditor.jython import JythonDev JythonDev.debug = 2 # Grab the ImagePlus from the most recently activated Fiji image window imp = IJ.getImage() # Convert the image to an ImgLib2 image img = IL.wrap(imp) # Show it IL.show(img, "wrapped as an ImgLib2 image") # Extend it: an infinite view extendedView = Views.extendMirrorSingle(img) # RandomAccessible # View with a larger canvas width = img.dimension(0) # same as imp.getWidth() height = img.dimension(1) # same as imp.getHeight() # from half an image beyond 0,0 (to the left and up) to half an image beyond width,height imgExtended = Views.interval(extendedView, [-width / 2, -height / 2], [width + width / 2 - 1, height + height / 2 - 1 ]) # RandomAccessibleInterval IL.show(imgExtended, "enlarged canvas with extended mirror symmetry")
#@ UIService ui # Run a HWatershed filter on all the frames along the TIME axis. # After the filtering step the image is clipped to match the input type. # Varun n Claudia H Watershed segmentation macro from net.imagej.axis import Axes from net.imglib2.algorithm.labeling.ConnectedComponents import StructuringElement from net.imglib2.roi.labeling import LabelRegions from net.imglib2.img.display.imagej import ImageJFunctions as IJF from net.imglib2.roi import Regions from net.imglib2.algorithm.neighborhood import HyperSphereShape from net.imagej.axis import CalibratedAxis from net.imglib2.view import Views import os from net.imagej.axis import Axes from net.imagej import ImgPlus name = os.path.basename(os.path.splitext(data.getImgPlus().name)[0]) axes = [Axes.X, Axes.Y, Axes.TIME] dataImg = ImgPlus(data.getImgPlus().copy(), "Result", axes) original = ops.convert().float32(dataImg) converted = ops.filter().gauss(original, blurradius) imp = IJF.show(converted) # H-watershed returns a label map as an ImagePlus labelimage = ops.run("H_Watershed", imp, hMin, thresh, peakFlooding, outputMask, allowSplit) ui.show(labelimage)
tempCLImage = clij.createCLImage( [inputCLImage.getWidth(), inputCLImage.getHeight()], inputCLImage.getChannelDataType()) outputCLImage = clij.createCLImage( [inputCLImage.getWidth(), inputCLImage.getHeight()], inputCLImage.getChannelDataType()) # crop out a center plane of the 3D data set Kernels.copySlice(clij, inputCLImage, tempCLImage, 64) # apply a filter to the image using ClearCL / OpenCL clij.execute( filesPath + "differenceOfGaussian.cl", "subtract_convolved_images_2d_fast", { "input": tempCLImage, "output": outputCLImage, "radius": 6, "sigma_minuend": Float(1.5), "sigma_subtrahend": Float(3) }) # convert the result back to imglib2 and show it resultRAI = clij.convert(outputCLImage, RandomAccessibleInterval) ImageJFunctions.show(resultRAI) IJ.run("Enhance Contrast", "saturated=0.35") # clean up inputCLImage.close() tempCLImage.close() outputCLImage.close()
from ij import IJ from net.imglib2.img.display.imagej import ImageJFunctions as IJF from net.imglib2.view import Views from jarray import zeros from net.imglib2 import FinalInterval imp = IJ.getImage() image = IJF.wrap(imp) min = zeros(image.numDimensions(), 'l') max = zeros(image.numDimensions(), 'l') min[image.numDimensions() - 1] = 0 max[image.numDimensions() - 1] = image.dimension(image.numDimensions() - 1) - 1 min[image.numDimensions() - 2] = 0 max[image.numDimensions() - 2] = image.dimension(image.numDimensions() - 2) - 1 for d in range(0, image.numDimensions() - 2): min[d] = -10 max[d] = image.dimension(d) + 10 interval = FinalInterval(min, max) print(interval) infinite = Views.extendZero(image) IJF.show(Views.interval(infinite, interval))
from net.imglib2.img.array import ArrayImg from net.imglib2.img.basictypeaccess.array import LongArray from net.imglib2.util import Fraction from net.imglib2.img.display.imagej import ImageJFunctions as IJF #from net.imglib2.img.array import ArrayImgFactory #from net.imglib2.type.numeric.integer import LongType from ij import IJ from ini.trakem2.imaging import FastIntegralImage imp = IJ.getImage() pix = imp.getProcessor().getPixels() ii = FastIntegralImage.longIntegralImage(pix, imp.getWidth(), imp.getHeight()) bip = FastIntegralImage.scaleAreaAverage(im, imp.getWidth() + 1, imp.getHeight() + 1, imp.getWidth() / 4, imp.getHeight() / 4) ImagePlus("25%", ByteProcessor(imp.getWidth() / 4, imp.getHeight() / 4, bip, None)).show() arrayimg = ArrayImg(LongArray(im), [2049, 2049], Fraction()) # Fails: perhaps lacks a converter IJF.show(arrayimg)
from net.imglib2.converter import ComplexImaginaryFloatConverter from net.imglib2.converter import ComplexPhaseFloatConverter from net.imglib2.converter import ComplexRealFloatConverter # perform fft of the template # basic fft call with no parameters #templateFFT=ops.filter().fft(template.getImgPlus()) # alternatively to pass an outofbounds factory we have to pass every parameter. We want: # output='None', input=template, borderSize=10 by 10, fast='True', outOfBoundsFactor=OutOfBoundsMirrorExpWindowingFactory templateFFT = ops.filter().fft(None, template.getImgPlus(), [10, 10], True, OutOfBoundsMirrorExpWindowingFactory(0.25)) # display fft (by default in generalized log power spectrum) ImageJFunctions.show(templateFFT).setTitle("fft power spectrum") # display fft phase spectrum ImageJFunctions.show( templateFFT, ComplexPhaseFloatConverter()).setTitle("fft phase spectrum") # display fft real values ImageJFunctions.show(templateFFT, ComplexRealFloatConverter()).setTitle("fft real values") # display fft imaginary values ImageJFunctions.show( templateFFT, ComplexImaginaryFloatConverter()).setTitle("fft imaginary values") # complex invert the fft of the template
from net.imglib2.img.display.imagej import ImageJFunctions; from net.imglib2.type.numeric.complex import ComplexFloatType; from net.imglib2.outofbounds import OutOfBoundsMirrorExpWindowingFactory; from jarray import array # perform fft of the template # basic fft call with no parameters #templateFFT=ops.fft(template.getImgPlus()) # alternatively to pass an outofbounds factory we have to pass every parameter. We want: # output='None', input=template, borderSize=10 by 10, fast='True', outOfBoundsFactor=OutOfBoundsMirrorExpWindowingFactory templateFFT=ops.fft(None, template.getImgPlus(), array([10, 10], 'l'), True, OutOfBoundsMirrorExpWindowingFactory(0.25)); ImageJFunctions.show(templateFFT).setTitle("fft power spectrum"); # complex invert the fft of the template c = ComplexFloatType(); for t in templateFFT: c.set(t); t.complexConjugate(); c.mul(t); t.div(c); # create Img memory for inverse FFT and compute inverse templateInverse=ops.createimg(array([template.dimension(0), template.dimension(1)], 'l')) ops.ifft(templateInverse, templateFFT) display.createDisplay("template inverse", templateInverse)
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")
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. s = [0.5 for d in xrange(img1.numDimensions())] img1s = Views.interval( RealViews.transform( Views.interpolate(Views.extendValue(img1M, zero), NLinearInterpolatorFactory()), Scale(s)), [0 for d in xrange(img1M.numDimensions())], [ int(img1M.dimension(d) / 2.0 + 0.5) - 1 for d in xrange(img1M.numDimensions()) ]) img2s = Views.interval( RealViews.transform( Views.interpolate(Views.extendValue(img2M, zero),
lLaser.setLaserOn(True); lLaser.setLaserPowerOn(True); # Take an image lImage = lScope.getDirectImage(); lImage.setImageWidth(1024); lImage.setImageHeight(2048); lImage.setIlluminationZ(25); lImage.setDetectionZ(25); # start acquisition img = EasyScopyUtilities.stackToImg(lImage.acquire()); # show the images ImageJFunctions.show(img); IJ.run("Enhance Contrast", "saturated=0.35"); # take an imagestack lImageStack = lScope.getDirectImageStack(); lImageStack.setImageWidth(1024); lImageStack.setImageHeight(2048); lImageStack.setIlluminationZ(25); lImageStack.setDetectionZ(25); lImageStack.setNumberOfRequestedImages(10); lImageStack.setDetectionZStepDistance(1); lImageStack.setIlluminationZStepDistance(1); # start acquisition imgStack = EasyScopyUtilities.stackToImg(lImageStack.acquire());
cache_loader = SoftRefLoaderCache().withLoader(loader) # SoftReference # Load the first image via the loader so that it's cached # and read the dimensions first = cache_loader.get( 0 ) # a Cell that wraps the ShortArray for the image pixels of the slice at index 0 width = first.dimension(0) height = first.dimension(1) depth = len( filepaths) # assumption: all files have the same dimensions and pixel type volume_dimensions = [width, height, depth] cell_dimensions = [width, height, 1] # just one image, one stack slice # The layout of cells: in this case, each Cell is a stack slice grid = CellGrid(volume_dimensions, cell_dimensions) img = CachedCellImg( grid, # the data layout UnsignedShortType( ), # for 16-bit images, each with a short[] native arrays cache_loader, # the loader, with a SoftReference cache ArrayDataAccessFactory.get(PrimitiveType.SHORT, AccessFlags.setOf(AccessFlags.VOLATILE))) IL.show( img, "Virtual stack: lazy-loading cached CellImg of a whole directory of images" )
n_cols = self.grid.imgDimension(0) / self.grid.cellDimension(0) x0 = (index % n_cols) * self.grid.cellDimension(0) y0 = (index / n_cols) * self.grid.cellDimension(1) index += 1 # 1-based slice indices in ij.ImageStack if index < 1 or index > self.imp.getStack().size(): # Return blank image: a ByteAccess that always returns 255 return Cell( self.cell_dimensions, [x0, y0], type('ConstantValue', (ByteAccess, ), { 'getValue': lambda self, index: 255 })()) else: return Cell( self.cell_dimensions, [x0, y0], ByteArray(self.imp.getStack().getProcessor(index).getPixels())) n_cols = 12 n_rows = 10 cell_width = imp.getWidth() cell_height = imp.getHeight() grid = CellGrid([n_cols * cell_width, n_rows * cell_height], [cell_width, cell_height]) montage = LazyCellImg(grid, img.cursor().next().createVariable(), SliceGet(imp, grid)) IL.show(montage, "Montage")
# Let's pick a pixel coordinate in 2D pos[0] = 128 pos[1] = 200 ra = img.randomAccess() ra.setPosition(pos) t = ra.get() # returns the Type class, which could be e.g. UnsignedByteType # which provides access to the pixel at that position print type(t) # Print the Type class # To print the pixel value, it's one level of indirection away, so do any of: print t.get() # the native primitive type, e.g., byte print t.getRealFloat() print t.getRealDouble() # To copy two images that are compatible in their iteration order, use cursors: cursor = img.cursor() cursor2 = img2.cursor() for t in cursor: cursor2.next().setReal(t.getRealFloat()) # The above is very slow in jython due to iteration overheads. # Instead, do: (as fast as possible, even multithreaded) ImgUtil.copy(img, img2) ImageJFunctions.show(img2, "copied") # For low-level operations in jython, you can inline small snippets of java code using the Weaver. # Search for "Weaver" in the tutorial for several examples: # https://syn.mrc-lmb.cam.ac.uk/acardona/fiji-tutorial
def factory(self): return None def copy(self): return self # stateless, so safe def randomAccess( self, interval=None ): # optional argument handles case of having randomAccess() and randomAccess(interval). return self.cursor() def cursor(self): return FnCursor(self.numDimensions(), -pi / 2, self.dimension(0) / 4) def localizingCursor(self): return self.cursor() img = FnImg([512, 512]) IL.show(img) # shows black, yet above the get() prints values aimg = ArrayImgs.floats([512, 512]) c1 = img.cursor() c2 = aimg.cursor() while c2.hasNext(): t = c2.next() c1.setPosition(c2) c2.next().set(c1.get()) IL.show(aimg) # Shows black, yet above the get() prints values
listt = [] listt_2 = [] for i in range(0, 3): listt.append(WindowManager.getImage(i + 1)) listt_2.append(ImagePlusAdapter.wrap(listt[i])) map = {'A': listt_2[0], 'B': listt_2[1], 'C': listt_2[2]} expression = '(A+B+C)/3' # Instantiate plugin parser = Image_Expression_Parser() # Configure & execute parser.setImageMap(map) parser.setExpression(expression) parser.process() result = parser.getResult() # is an ImgLib image result_imp = ImageJFunctions.show(result) IJ.run('Rename...', 'title=AverageIMG') result_img = ImagePlusAdapter.wrap(result_imp) mean_average = result_imp.getStatistics() mean_average = mean_average.mean scaled_list = [] for i in range(0, 3): imp = listt[i] img = listt_2[i] map = {'A': img, 'B': result_imp} mean_img = imp.getStatistics() mean_img = mean_img.mean expression = 'A-(0.9*mean_img/mean_average*B)' parser = Image_Expression_Parser() # Configure & execute parser.setImageMap(map)
from org.python.core import codecs codecs.setDefaultEncoding('utf-8') import os from java.io import File from ij import ImageJ, ImagePlus from ij.io import Opener from net.imglib2.img import Img, ImgFactory from net.imglib2.img.cell import CellImgFactory from net.imglib2.img.display.imagej import ImageJFunctions from net.imglib2.type.numeric.real import FloatType gitDir = os.environ['GIT_HOME'] relImg = "/OSImageAnalysis/images" # strImg = gitDir + relImg + "/bridge.gif" strImg = gitDir + relImg + "/latex.tif" fi = File(strImg) imp = Opener().openImage( fi.getAbsolutePath() ) imp.show() imgFactory = CellImgFactory(5 ) img1 = imgFactory.create( (20, 30, 40), FloatType() ) ImageJFunctions.show( img1 ) img2 = imgFactory.create( img1, img1.firstElement() ) ImageJFunctions.show( img2 )
from net.imglib2.converter import ComplexPhaseFloatConverter from net.imglib2.converter import ComplexRealFloatConverter from jarray import array # perform fft of the template # basic fft call with no parameters templateFFT = ops.filter().fft(template.getImgPlus()) # alternatively to pass an outofbounds factory we have to pass every parameter. We want: # output='None', input=template, borderSize=10 by 10, fast='True', outOfBoundsFactor=OutOfBoundsMirrorExpWindowingFactory # templateFFT=ops.fft(None, template.getImgPlus(), array([10, 10], 'l'), True, OutOfBoundsMirrorExpWindowingFactory(0.25)); # display fft (by default in generalized log power spectrum) ImageJFunctions.show(templateFFT).setTitle("fft power spectrum") # display fft phase spectrum ImageJFunctions.show(templateFFT, ComplexPhaseFloatConverter()).setTitle("fft phase spectrum") # display fft real values ImageJFunctions.show(templateFFT, ComplexRealFloatConverter()).setTitle("fft real values") # display fft imaginary values ImageJFunctions.show(templateFFT, ComplexImaginaryFloatConverter()).setTitle("fft imaginary values") # complex invert the fft of the template c = ComplexFloatType() for t in templateFFT: c.set(t) t.complexConjugate()
from net.imglib2.type.numeric.complex import ComplexFloatType from net.imglib2.outofbounds import OutOfBoundsMirrorExpWindowingFactory from jarray import array # perform fft of the template # basic fft call with no parameters #templateFFT=ops.fft(template.getImgPlus()) # alternatively to pass an outofbounds factory we have to pass every parameter. We want: # output='None', input=template, borderSize=10 by 10, fast='True', outOfBoundsFactor=OutOfBoundsMirrorExpWindowingFactory templateFFT = ops.fft(None, template.getImgPlus(), array([10, 10], 'l'), True, OutOfBoundsMirrorExpWindowingFactory(0.25)) ImageJFunctions.show(templateFFT).setTitle("fft power spectrum") # complex invert the fft of the template c = ComplexFloatType() for t in templateFFT: c.set(t) t.complexConjugate() c.mul(t) t.div(c) # create Img memory for inverse FFT and compute inverse templateInverse = ops.createimg( array([template.dimension(0), template.dimension(1)], 'l')) ops.ifft(templateInverse, templateFFT) display.createDisplay("template inverse", templateInverse)