def thresholdStackW(imp, low, high): i = 1 stack = imp.getStack() depth = imp.getNSlices() print "thresholdStackW: depth", depth width = stack.getProcessor(i).getWidth() height = stack.getProcessor(i).getHeight() winput = [None] w = Weaver.inline( """ byte[] input = (byte[]) winput.get(0); byte[] output = new byte[input.length]; for (int i=0; i<input.length; i++) { if (input[i] < low || input[i] > high){ output[i] = (byte)0; } else { output[i] = (byte)255; } } return output; """, {"winput":winput, "low":low, "high":high}) stackout = ImageStack(width, height) for k in range(1, depth+1): ip = stack.getProcessor(k) winput[0] = ip.getPixels() pixels = w.call() ipout = ByteProcessor(width, height) ipout.setPixels(pixels) stackout.addSlice(ipout) imp.setStack(stackout)
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 Inline(arrays): return Weaver.inline( """ int[] pixelst = (int[])arrays.get(0); int[] pixelsd = (int[])arrays.get(1); double sum = 0; for (int i=0; i<pixelst.length; i++) { int t = pixelst[i]; int d = pixelsd[i]; int red = ((t >> 16)&0xff) - ((d >> 16)&0xff); int green = ((t >> 8)&0xff) - ((d >> 8)&0xff); int blue = (t&0xff) - (d&0xff); //sum += Math.sqrt(red * red + green * green + blue * blue); sum += red * red + green * green + blue * blue; } return sum; """, {"arrays": arrays})
def Inline(arrays): return Weaver.inline( """ int[] pixelst = (int[])arrays.get(0); int[] pixelsd = (int[])arrays.get(1); double sum = 0; for (int i=0; i<pixelst.length; i++) { int t = pixelst[i]; int d = pixelsd[i]; int red = ((t >> 16)&0xff) - ((d >> 16)&0xff); int green = ((t >> 8)&0xff) - ((d >> 8)&0xff); int blue = (t&0xff) - (d&0xff); //sum += Math.sqrt(red * red + green * green + blue * blue); sum += red * red + green * green + blue * blue; } return sum; """, {"arrays" : arrays})
imap(FloatType.getRealFloat, hsc)) # ~1.5x faster than for t in hsc: s += t.getRealFloat #intensities2.append(float(s) / size) t2 = System.currentTimeMillis() print "Elapsed time:", (t2 - t1), "ms" w = Weaver.inline( """ double sum = 0; //final net.imglib2.Cursor<net.imglib2.type.numeric.real.FloatType> c = (net.imglib2.Cursor<net.imglib2.type.numeric.real.FloatType>) hsc; final Cursor<FloatType> c = (Cursor<FloatType>) hsc; while (c.hasNext()) { c.fwd(); sum += c.get().getRealFloat(); } // Fails, for some reason //for (final net.imglib2.type.numeric.real.FloatType t : c) { // sum += t.getRealFloat(); //} return sum; """, {"hsc": hsc}, Double, True, [FloatType, Cursor]) t3 = System.currentTimeMillis() for i in xrange(100): for peak in peaks: hsc.updateCenter([int(peak[0]), int(peak[1]), int(peak[2])]) #s = sum(imap(FloatType.getRealFloat, hsc)) s = w.call()
from jarray import zeros, array from java.nio import ByteBuffer, ByteOrder from fiji.scripting import Weaver from java.lang import Class, Integer from net.imglib2.img.display.imagej import ImageJFunctions as IL w = Weaver.method(""" static public final short[][] deinterleave(final short[] source, final int numChannels, final int channel_index) { if (channel_index >= 0) { // Read a single channel final short[] shorts = new short[source.length / numChannels]; for (int i=channel_index; k=0; i<source.length; ++k, i+=numChannels) { shorts[k] = source[i]; } return new short{shorts}; } final short[][] channels = new short[numChannels][source.length / numChannels]; for (int i=0, k=0; i<source.length; ++k) { for (int c=0; c<numChannels; ++c, ++i) { channels[c][k] = source[i]; } } return channels; } """, [], False) # no imports, and don't show code print w from org.scijava.plugins.scripting.clojure import ClojureScriptEngine clj = ClojureScriptEngine() code = """
print event def update_roi_mappings(): global roi_in global roi_ni for i in range(roimgr.getCount()): name = roimgr.getName(i) roi_in.append(name) roi_ni[name] = i wcode = Weaver.inline( """ javax.swing.AbstractListModel m = new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }; return m; """, {}, javax.swing.AbstractListModel) print "Weaver created!" listmodel = wcode.call() print "Weaver called!" roimgr = RoiManager.getInstance() if roimgr is None: print "No ROIs defined." sys.exit(0) roi_ni = {} roi_in = [] update_roi_mappings()
ws = Weaver.method( """ public final class Spheres extends RealPoint implements RealRandomAccess { private final KDTree kdtree; private final NearestNeighborSearchOnKDTree search; private final double radius, radius_squared; private final UnsignedShortType inside, outside; public Spheres(final KDTree kdtree, final double radius, final UnsignedShortType inside, final UnsignedShortType outside) { super(3); this.kdtree = kdtree; this.radius = radius; this.radius_squared = radius * radius; this.inside = inside; this.outside = outside; this.search = new NearestNeighborSearchOnKDTree(kdtree); } public final Spheres copyRealRandomAccess() { return new Spheres(this.kdtree, this.radius, this.inside, this.outside); } public final Spheres copy() { return copyRealRandomAccess(); } public final UnsignedShortType get() { this.search.search(this); if (this.search.getSquareDistance() < this.radius_squared) { return inside; } return outside; } } public final Spheres createSpheres(final KDTree kdtree, final double radius, final UnsignedShortType inside, final UnsignedShortType outside) { return new Spheres(kdtree, radius, inside, outside); } """, [ RealPoint, RealRandomAccess, KDTree, NearestNeighborSearchOnKDTree, UnsignedShortType ])
from ij.process import ByteProcessor M = Weaver.method( """ public final int mandelbrot(final double re0, final double im0, final int maxIterations) { double re = re0; double im = im0; int i = 0; for ( ; i < maxIterations; ++i ) { final double squre = re * re; final double squim = im * im; if ( squre + squim > 4 ) break; im = 2 * re * im + im0; re = squre - squim + re0; } return i; } public final void into(final RealRandomAccess rra, final Cursor cursor, final double scale, final double[] offset) { while (cursor.hasNext()) { UnsignedByteType t = (UnsignedByteType) cursor.next(); for ( int d = 0; d < 2; ++d ) { rra.setPosition( scale * cursor.getIntPosition( d ) + offset[ d ], d ); } t.set( (UnsignedByteType) rra.get() ); } } """, [RealPoint, RealRandomAccess, Cursor, UnsignedByteType])
vol4d = LazyCellImg(grid, first.randomAccess().get().createVariable(), TimePointGet(timepoint_paths)) print dimensions # Visualization option 2: # Create a 4D VirtualStack manually # Need a fast way to copy pixel-wise w = Weaver.method( """ static public final void copy(final Cursor src, final Cursor tgt) { while (src.hasNext()) { src.fwd(); tgt.fwd(); final UnsignedShortType t1 = (UnsignedShortType) src.get(), t2 = (UnsignedShortType) tgt.get(); t2.set(t1.get()); } } """, [Cursor, UnsignedShortType]) class Stack4D(VirtualStack): def __init__(self, img4d): super(VirtualStack, self).__init__(img4d.dimension(0), img4d.dimension(1), img4d.dimension(2) * img4d.dimension(3)) self.img4d = img4d self.dimensions = array([img4d.dimension(0), img4d.dimension(1)], 'l')
p = zeros(3, 'l') cursor = img1.cursor() middle = Point3f(49.5, 49.5, 49.5) distance_sq = float(30 * 30) w = Weaver.method( """ public void fillSphere(final Cursor cursor, final Point3f middle, final float distance_sq) { final long[] p = new long[cursor.numDimensions()]; while (cursor.hasNext()) { cursor.fwd(); cursor.localize(p); final UnsignedByteType t = (UnsignedByteType) cursor.get(); if (middle.distanceSquared(new Point3f( (float)p[0], (float)p[1], (float)p[2] ) ) < distance_sq) { t.setOne(); } else { t.setZero(); } } } public void fillOnes(final Cursor cursor) { while (cursor.hasNext()) { ((UnsignedByteType)cursor.next()).setOne(); } } """, [Cursor, Point3f, UnsignedByteType]) w.fillSphere(img1.cursor(), middle, distance_sq) imp1 = IL.wrap(img1, "sphere") imp1.setDisplayRange(0, 1)
hsc.updateCenter([int(peak[0]), int(peak[1]), int(peak[2])]) s = sum( imap(FloatType.getRealFloat, hsc)) # ~1.5x faster than for t in hsc: s += t.getRealFloat #intensities2.append(float(s) / size) t2 = System.currentTimeMillis() print "Elapsed time:", (t2 - t1), "ms" o = Weaver.method( """ static public double sum(final HyperSphereCursor<FloatType> hsc) { double sum = 0; while (hsc.hasNext()) { hsc.fwd(); sum += hsc.get().getRealFloat(); } return sum; } """, [FloatType, HyperSphereCursor], True) t3 = System.currentTimeMillis() for i in xrange(100): for peak in peaks: hsc.updateCenter([int(peak[0]), int(peak[1]), int(peak[2])]) s = o.sum(hsc) #intensities2.append(float(s) / size) t4 = System.currentTimeMillis()
print dimensions # Visualization option 1: # An automatically created 4D VirtualStack #IL.wrap(vol4d, "Volume 4D").show() # Visualization option 2: # Create a 4D VirtualStack manually # Need a fast way to copy pixel-wise w = Weaver.method( """ static public final void copy(final Cursor src, final Cursor tgt) { while (src.hasNext()) { src.fwd(); tgt.fwd(); final UnsignedShortType t1 = (UnsignedShortType) src.get(), t2 = (UnsignedShortType) tgt.get(); t2.set(t1.get()); } } """, [Cursor, UnsignedShortType]) class Stack4D(VirtualStack): def __init__(self, img4d): super(VirtualStack, self).__init__(img4d.dimension(0), img4d.dimension(1), img4d.dimension(2) * img4d.dimension(3)) self.img4d = img4d self.dimensions = array([img4d.dimension(0), img4d.dimension(1)], 'l')
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/" 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 ImagePlus target, final String path) { ImagePlus imp = IJ.openImage(path); ImageStack stack1 = target.getStack(); ImageStack stack2 = imp.getStack(); ImageProcessor ip1, ip2; for (int i=0; i < stack1.getSize(); ++i) { ip1 = stack1.getProcessor(i+1); ip2 = stack2.getProcessor(i+1); final int count = ip1.getWidth() * ip1.getHeight(); for (int k=0; k<count; ++k) { ip1.setf(k, Math.max( ip1.getf(k), ip2.getf(k) ) ); } } stack1 = null; stack2 = null; imp.setIgnoreFlush(false); imp.unlock(); imp.flush(); imp = null; } """, [IJ, ImagePlus, ImageStack, ImageProcessor, Math]) max_imp = None 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_imp is None: max_imp = IJ.openImage(path) else: java.maxer(max_imp, path) num_timepoints -= 1 if num_timepoints < 0: break # DONE max_imp.show()
from fiji.scripting import Weaver from ij import IJ from ij import ImagePlus from ij import ImageStack # The currently open image, an 8-bit stack imp = IJ.openImage("http://imagej.net/images/bat-cochlea-volume.zip") slices = [None, None] w = Weaver.inline( """ byte[] pix1 = (byte[]) slices.get(0); byte[] pix2 = (byte[]) slices.get(1); byte[] xor = new byte[pix1.length]; for (int i=0; i<pix1.length; i++) { xor[i] = (byte)(pix1[i] ^ pix2[i]); } return xor; """, {"slices" : slices}) stack = imp.getStack() stackXOR = ImageStack(stack.width, stack.height) for i in range(2, imp.getNSlices()+1): # Put the pixel arrays into the pre-made list slices[0] = stack.getPixels(i-1) slices[1] = stack.getPixels(i) # Invoke native code stackXOR.addSlice( str(i-1), w.call() )