Example #1
0
def test(iraf):

    # Test dimensions: should be the same as the one input image
    print "Dimensions:", Intervals.dimensionsAsLongArray(iraf)

    # Test Cursor
    c = iraf.cursor()
    pos = zeros(2, 'l')
    while c.hasNext():
        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()
Example #2
0
 def openImage():
   print rel_path
   if rel_path.endswith(".klb"):
     try:
       klb = KLB.newInstance()
       img = klb.readFull(os.path.join(base_path, rel_path))
       IL.wrap(img, rel_path).show()
     except:
       print sys.exc_info()
   else:
     print "via IJ.open"
     IJ.open(os.path.join(base_path, rel_path))
Example #3
0
 def openImage():
     print rel_path
     if rel_path.endswith(".klb"):
         if (KLB == None):
             print "Cannot open KLB due to missing module"
         try:
             klb = KLB.newInstance()
             img = klb.readFull(os.path.join(base_path, rel_path))
             IL.wrap(img, rel_path).show()
         except:
             print sys.exc_info()
     else:
         print "via IJ.open"
         IJ.open(os.path.join(base_path, rel_path))
Example #4
0
def showAsComposite(images, title="Composite", show=True):
    imps = []
    # Collect all images as ImagePlus, checking that they have the same XY dimensions.
    # (Z doesn't matter)
    dimensions = None
    for img in images:
        if isinstance(img, ImagePlus):
            imps.append(img)
        else:
            imps.append(IL.wrap(img, ""))
        if not dimensions:
            dimensions = [imps[-1].getWidth(), imps[-1].getHeight()]
        else:
            if imps[-1].width != dimensions[0] or imps[-1].getHeight(
            ) != dimensions[1]:
                print "asComposite: dimensions mistach."
                return
    imp = ImagePlus(title, StacksAsChannels([imp.getStack() for imp in imps]))
    imp.setDimensions(len(imps), max(imp.getStack().getSize() for imp in imps),
                      1)
    comp = CompositeImage(imp, CompositeImage.COMPOSITE)
    if show:
        comp.show()
    print imp.getNChannels(), imp.getNSlices(), imp.getNFrames(
    ), "but imps: ", len(imps)
    return comp
 def __init__(self, imp, cell_padding, padding_color_value, grid):
     self.stack = imp.getStack()
     self.grid = grid
     self.cell_padding = cell_padding
     self.t = IL.wrap(imp).randomAccess().get().createVariable()
     self.t.setReal(padding_color_value)
     self.cache = {}
 def create(self, index):
     cell_dimensions = [
         self.grid.cellDimension(0),
         self.grid.cellDimension(1)
     ]
     n_cols = grid.imgDimension(0) / cell_dimensions[0]
     x0 = (index % n_cols) * cell_dimensions[0]
     y0 = (index / n_cols) * cell_dimensions[1]
     index += 1  # 1-based slice indices in ij.ImageStack
     if index < 1 or index > self.stack.size():
         # Return blank image: a ByteAccess that always returns 255
         return Cell(
             cell_dimensions, [x0, y0],
             type('ConstantValue', (ByteAccess, ), {
                 'getValue': lambda self, index: 255
             })())
     else:
         # ImageJ stack slice indices are 1-based
         img = IL.wrap(ImagePlus("", self.stack.getProcessor(index)))
         # Create extended image with the padding color value
         imgE = Views.extendValue(img, self.t.copy())
         # A view that includes the padding between slices
         minC = [-self.cell_padding for d in xrange(img.numDimensions())]
         maxC = [
             img.dimension(d) - 1 + self.cell_padding
             for d in xrange(img.numDimensions())
         ]
         imgP = Views.interval(imgE, minC, maxC)
         return Cell(cell_dimensions, [x0, y0],
                     ProxyByteAccess(imgP, self.grid))
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 twoStep(index=0):
    # The current way:
    img = klb.readFull(filepaths[index])  # klb_loader.get(filepaths[index])
    imgE = Views.extendZero(img)
    imgI = Views.interpolate(imgE, NLinearInterpolatorFactory())
    imgT = RealViews.transform(imgI, cmIsotropicTransforms[index])
    imgB = Views.zeroMin(Views.interval(imgT, roi[0],
                                        roi[1]))  # bounded: crop with ROI
    imgBA = ArrayImgs.unsignedShorts(Intervals.dimensionsAsLongArray(imgB))
    ImgUtil.copy(ImgView.wrap(imgB, imgBA.factory()), imgBA)
    imgP = prepareImgForDeconvolution(
        imgBA,
        affine3D(fineTransformsPostROICrop[index]).inverse(),
        FinalInterval([0, 0, 0], [imgB.dimension(d) - 1 for d in xrange(3)]))
    # 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, "two step").show()
Example #9
0
def main():
    img = IJF.wrap(imp)

    img_out = smooth_temporal_gradient(ops, img, sigma_xy, sigma_t,
                                       frame_start, frame_end,
                                       normalize_output)
    img_out.setCalibration(imp.getCalibration().copy())
    comp = CompositeImage(img_out, CompositeImage.COMPOSITE)
    comp.show()
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()
Example #11
0
def showStack(img, title="", proper=True, n_channels=1):
    # IL.wrap fails: shows slices as channels, and channels as frames
    if not proper:
        imp = IL.wrap(img, title)
        imp.show()
        return imp
    # Proper sorting of slices, channels and frames
    imp = wrap(img, title=title, n_channels=n_channels)
    comp = CompositeImage(
        imp,
        CompositeImage.GRAYSCALE if 1 == n_channels else CompositeImage.COLOR)
    comp.show()
    return comp
Example #12
0
def writeZip(img, path, title=""):
  if isinstance(img, RandomAccessibleInterval):
    imp = IL.wrap(img, title)
  elif isinstance(img, ImagePlus):
    imp = img
    if title:
      imp.setTitle(title)
  else:
    syncPrint("Cannot writeZip to %s:\n  Unsupported image type %s" % (path, str(type(img))))
    return None
  #
  FileSaver(imp).saveAsZip(path)
  return imp
def getMIP(imp): 
	if isinstance(imp,ImagePlus):
		im = ImageJFunctions.wrap(imp)
	else:
		im = imp	
	
	projected = ops.create().img([ im.dimension(d) for d in [0,1] ])
	
	# Create the op and run it
	proj_op = ops.op(getattr(Ops.Stats, "Max"), im)
	ops.transform().project(projected, im, proj_op, 2)
	
	return projected
def maskFromOverlay(imp):
  ''' TODO Documentation '''
  overlay = imp.getOverlay();
  
  img = ImageJFunctions.wrap(imp);
  emptyImg = ops.create().img(img);
  if overlay is None:
  	return emptyImg;
  
  emptyImp = ImageJFunctions.wrap(emptyImg, "mask");
  
  for roi in overlay.toArray():
    imp.setRoi(roi);
    IJ.run(imp, "Create Mask", "");
    manualMaskImp = IJ.getImage();
    ic = ImageCalculator();
    ic.run("OR", emptyImp, manualMaskImp);
  
  manualMask = ImageJFunctions.wrap(manualMaskImp);
  manualMaskImp.close();
  #imp.setRoi(None);
  
  return manualMask;
Example #15
0
def viewTransformed(image,
                    transformation,
                    title=None,
                    interval=None,
                    show=True):
    if isinstance(image, ImagePlus):
        img = IL.wrap(
            image
        )  # ImagePlus to ImgLib2 RandomAccessibleInterva & IterableInterval aka Img
    elif isinstance(image, RandomAccessibleInterval):
        img = image
    else:
        return None
    # Make the image be defined anywhere by infinitely padding with zeros.
    imgInfinite = Views.extendZero(img)
    # Make the image be defined at arbitrarily precise subpixel coordinates
    # by using n-dimensional linear interpolation
    imgInterpolated = Views.interpolate(imgInfinite,
                                        NLinearInterpolatorFactory())
    # Make the image be seen as a transformed view of the source image
    imgTransformed = RealViews.transform(imgInterpolated, transformation)
    # Define an interval within which we want the transformed image to be defined
    # (such as that of the source img itself; an img in ImgLib2 also happens to be an Interval
    # and can therefore be used as an interval, which is convenient here because we
    # expect the original field of view--the interval--to be where image data can still be found)
    interval = interval if interval else img  # every Img is also an Interval because each Img is bounded
    # Make the image finite by defining it as the content within the interval
    imgBounded = Views.interval(imgTransformed, interval)  # same as original
    # Optionally show the transformed, bounded image in an ImageJ VirtualStack
    # (Note that anytime one of the VirtualStack's ImageProcessor will have to
    # update its pixel data, it will incur in executing the transformation again;
    # no pixel data is cached or copied anywhere other than for display purposes)
    if show:
        title = title if title else imp.getTitle()
        imp = IL.wrap(imgBounded, title)  # as an ImagePlus
        imp.show()  # in an ImageJ ImageWindow
    return imgBounded
def main():
    files = []
    for filt in img_extensions.split(";"):
        if len(filt.strip()) > 0:
            files += glob.glob(os.path.join(str(input_dir), filt.strip()))
        else:
            files += glob.glob(os.path.join(str(input_dir), "*.*"))
            break

    if len(files) == 0:
        IJ.showMessage("No files found in '{}'\nfor extensions '{}'".format(
            str(input_dir), img_extensions))
    else:
        for fn in files:
            try:
                imp = BF.openImagePlus(fn)[0]
            except:
                IJ.showMessage(
                    "Could not open file '{}' (skipping).\nUse extension filter to filter non-image files..."
                    .format(str(fn)))
                continue

            img = IJF.wrap(imp)

            cali = imp.getCalibration().copy()
            if pixel_width > 0:
                cali.pixelWidth = pixel_width
                cali.pixelHeight = pixel_width
                cali.setUnit("micron")
            if frame_interval > 0:
                cali.frameInterval = frame_interval
                cali.setTimeUnit("sec.")

            imp_out = smooth_temporal_gradient(ops, img, sigma_xy, sigma_t,
                                               frame_start, frame_end,
                                               normalize_output)
            imp_out.setCalibration(cali)

            channels = ChannelSplitter.split(imp_out)

            fn_basename = os.path.splitext(fn)[0]
            IJ.save(channels[0], "{}_shrinkage.tiff".format(fn_basename))
            IJ.save(channels[1], "{}_growth.tiff".format(fn_basename))

            print("{} processed".format(fn_basename))

        IJ.showMessage(
            "Growth/shrinkage extraction of {} inputs finsihed.".format(
                len(files)))
Example #17
0
def wrap(img, title="", n_channels=1):
    """ Like ImageJFunctions.wrap but, when n_channels=1 (the default),
      then a new dimension of size 1 is inserted at position 2 to prevent the Z axis
      from showing as the channels axis.
      To enable ImageJFunctions.wrap default behavior, set n_channels to a value other than 1. """
    if 1 == n_channels:
        # Append a dimension of size 1 at the end
        # and permute it iteratively so that it becomes the channels dimension (d=2)
        img = Views.addDimension(img, 1, 1)
        d = img.numDimensions(
        ) - 1  # starts with the last: the new one of size 1
        while d > 2:
            img = Views.permute(img, d, d - 1)
            d -= 1
    #
    return IL.wrap(img, title)
def SpotDetectionGray(gray, data, display, ops, invert):

    # get the dimensions
    dimensions2D = array([gray.dimension(0), gray.dimension(1)], 'l')
    factory = gray.getImg().factory()

    # wrap as ImagePlus
    imp = ImageJFunctions.wrap(gray, "wrapped")

    # create and call background subtractor
    bgs = BackgroundSubtracter()
    bgs.rollingBallBackground(imp.getProcessor(), 50.0, False, False, True,
                              True, True)

    # wrap the result of background subtraction as Img and display it
    iplus = ImagePlus("bgs", imp.getProcessor())

    #	if (invert==True):
    #		iplus.getProcessor().invert()

    imgBgs = ImageJFunctions.wrapByte(iplus)
    display.createDisplay("back_sub", data.create(ImgPlus(imgBgs)))

    # convert the background subtracted image to 32 bit
    temp = ops.run("createimg", factory, FloatType(), dimensions2D)
    imgBgs32 = ImgPlus(temp)
    ops.convert(imgBgs32, imgBgs, ConvertPixCopy())
    #display.createDisplay("back_sub 32", data.create(ImgPlus(imgBgs32)))

    # create the Laplacian of Gaussian filter
    kernel = DetectionUtils.createLoGKernel(3.0, 2, array([1.0, 1.0], 'd'))

    # apply the log filter and display the result
    log = ImgPlus(ops.run("createimg", factory, FloatType(), dimensions2D))
    ops.convolve(log, imgBgs32, kernel)
    #display.createDisplay("log", data.create(ImgPlus(log)))

    # apply the threshold operation
    #thresholded=ops.run("threshold", ops.create( dimensions2D, BitType()), log, Triangle())
    thresholded = ops.run("triangle", log)

    return ImgPlus(thresholded)
def SpotDetectionGray(gray, data, display, ops, invert):
	
	# get the dimensions
	dimensions2D=array( [gray.dimension(0), gray.dimension(1)], 'l')
	factory=gray.getImg().factory()

	# wrap as ImagePlus
	imp=ImageJFunctions.wrap(gray, "wrapped")

	# create and call background subtractor
	bgs=BackgroundSubtracter()
	bgs.rollingBallBackground(imp.getProcessor(), 50.0, False, False, True, True, True) 
	
	# wrap the result of background subtraction as Img and display it
	iplus=ImagePlus("bgs", imp.getProcessor())

#	if (invert==True):
#		iplus.getProcessor().invert()
	
	imgBgs=ImageJFunctions.wrapByte(iplus)
	display.createDisplay("back_sub", data.create(ImgPlus(imgBgs))) 

	# convert the background subtracted image to 32 bit
	temp=ops.run( "createimg", factory, FloatType(), dimensions2D )
	imgBgs32=ImgPlus( temp )
	ops.convert(imgBgs32, imgBgs, ConvertPixCopy() )
	#display.createDisplay("back_sub 32", data.create(ImgPlus(imgBgs32))) 

	# create the Laplacian of Gaussian filter
	kernel = DetectionUtils.createLoGKernel( 3.0, 2, array([1.0, 1.0], 'd' ) )

	# apply the log filter and display the result
	log=ImgPlus( ops.run("createimg", factory, FloatType(), dimensions2D) )
	ops.convolve(log, imgBgs32, kernel)
	#display.createDisplay("log", data.create(ImgPlus(log)))
	
	# apply the threshold operation
	#thresholded=ops.run("threshold", ops.create( dimensions2D, BitType()), log, Triangle())
	thresholded = ops.run("triangle", log)
	
	return ImgPlus(thresholded)
Example #20
0
from mpicbg.models import Point, PointMatch, InterpolatedAffineModel3D, AffineModel3D, RigidModel3D, NotEnoughDataPointsException
from collections import defaultdict
from operator import sub
from itertools import imap, izip, product, combinations
from jarray import array, zeros
import os, csv
from java.util.concurrent import Executors, Callable
from java.util import ArrayList
from ij import IJ
from net.imglib2.algorithm.math import ImgMath, ImgSource
from net.imglib2.img.array import ArrayImgs
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)
Example #21
0
from net.imglib2.view import Views
from net.imglib2.img.array import ArrayImgs
from net.imglib2.util import Intervals, ImgUtil
from net.imglib2.algorithm.math.ImgMath import compute, maximum
from java.lang import Math

imp = IJ.getImage()
stack = imp.getStack()

# Grab the underlying ImgLib2 object, or wrap into one
if isinstance(stack, ImageJVirtualStack):
    srcF = ImageJVirtualStack.getDeclaredField("source")
    srcF.setAccessible(True)
    img4D = srcF.get(stack)
else:
    img4D = IL.wrap(imp)


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,
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	title =  inputImp.getTitle()
	title=title.replace('UV', 'SD')
	
	print title
	
	#trueColorImp= WindowManager.getImage(title)
	#print type( trueColorImp)
	
	# calculate are of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	print inputRoi
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1

	print x1
	print y1
	print x2
	print y2
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	#duplicate.show()
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	redPlus.show()
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	APlus.show()
	APlus.getProcessor().resetMinAndMax()
	APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	#redMask.show()
	
	labPlus.close()
	
	# threshold the spots from the red channel
	thresholdedred=SpotDetectionGray(red, data, display, ops, False)
	display.createDisplay("thresholdedred", data.create(thresholdedred))
	impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	
	# threshold the spots from the brightness channel
	thresholded=SpotDetectionGray(brightness, data, display, ops, False)
	display.createDisplay("thresholded", data.create(thresholded))
	impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, clone)
	
	# create a hidden roi manager
	roim = RoiManager(True)
	
	# count the particlesimp.getProcessor().setColor(Color.green)
	countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity)
	
	# define a function to determine the percentage of pixels that are foreground in a binary image
	# inputs:
	#    imp: binary image, 0=background, 1=foreground
	#    roi: an roi
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return False
		else: return True

	allList=[]

	for roi in roim.getRoisAsArray():
		allList.append(roi.clone())
	
	# count particles that are red
	redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed)
	# count particles that are red
	blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed)

	print "Total particles: "+str(len(allList))
	print "Filtered particles: "+str(len(redList))

	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList]
	
	# create an overlay and add the rois
	overlay1=Overlay()
		
	inputRoi.setStrokeColor(Color.green)
	overlay1.add(inputRoi)
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList]
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList]
	
	def drawAllRoisOnImage(imp, mainRoi, redList, blueList):
		imp.getProcessor().setColor(Color.green)
		IJ.run(imp, "Line Width...", "line=3");
		imp.getProcessor().draw(inputRoi)
		imp.updateAndDraw()
		IJ.run(imp, "Line Width...", "line=1");
		[CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList]
		[CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList]
		imp.updateAndDraw()
	
	drawAllRoisOnImage(inputImp, inputRoi, redList, blueList)
	#drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList)
	
	# draw overlay
	#inputImp.setOverlay(overlay1)
	#inputImp.updateAndDraw()
	
	statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	print inputRoiArea

	areas=statsdict['Areas']
	poreArea=0
	for area in areas:
		poreArea=poreArea+area

	ATotal=0
	ALevels=statsdict['ALevel']
	for A in ALevels:
		ATotal=ATotal+A

	AAverage=ATotal/len(ALevels)

	BTotal=0
	BLevels=statsdict['BLevel']
	for B in BLevels:
		BTotal=BTotal+B

	BAverage=BTotal/len(BLevels)

	redTotal=0
	redPercentages=statsdict['redPercentage']
	for red in redPercentages:
		redTotal=redTotal+red

	redAverage=redTotal/len(redPercentages)
	pixwidth=inputImp.getCalibration().pixelWidth

	inputRoiArea=inputRoiArea/(pixwidth*pixwidth)
	
	print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
display.createDisplay("red", data.create(red))
display.createDisplay("green", data.create(green))

red32=ImgPlus( ops.create( dimensions2D, FloatType()) )
ops.convert(red32, red, ConvertPixCopy() )

green32=ImgPlus( ops.create( dimensions2D, FloatType()) )
ops.convert(green32, green, ConvertPixCopy() )

redgreen= ops.add(red32,green32)
display.createDisplay("redgreen", data.create(redgreen))

# make a copy of the red + green image
copy=redgreen.copy()
# wrap as ImagePlus
imp=ImageJFunctions.wrap(copy, "wrapped")

# create and call background subtractor
bgs=BackgroundSubtracter()
bgs.rollingBallBackground(imp.getProcessor(), 50.0, False, False, True, True, True) 

# wrap as Img and display
iplus=ImagePlus("bgs", imp.getProcessor())
print type(imp)
imgBgs=ImageJFunctions.wrapFloat(iplus)
display.createDisplay("back_sub", data.create(ImgPlus(imgBgs))) 

kernel = DetectionUtils.createLoGKernel( 3.0, 2, array([1.0, 1.0], 'd' ) )

print type(kernel)
print type(imgBgs)
# 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,
        "max",
        maximum([var("red"), var("green"),
                 var("blue")]),
Example #25
0
from ij import IJ
from net.imglib2.algorithm.math.ImgMath import compute, maximum, minimum, log, exp, div, mul
from net.imglib2.algorithm.math import Print
from net.imglib2.converter import Converters, ColorChannelOrder
from net.imglib2.img.array import ArrayImgs
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from net.imglib2.view import Views

# Fetch an RGB image stack
imp_rgb = IJ.getImage(
)  # IJ.openImage("http://imagej.nih.gov/ij/images/flybrain.zip")

img = IL.wrap(imp_rgb)  # an ARGBType Img
# Color channel views
red, green, blue = (Converters.argbChannel(img, c) for c in [1, 2, 3])

# ImgLib1 scripting gamma function
# return Min(255, Max(0, Multiply(Exp(Multiply(gamma, Log(Divide(channel, 255)))), 255)))

gamma = 0.5


def op(channel):
    return minimum(
        255, maximum(0, mul(exp(mul(gamma, log(div(channel, 255)))), 255)))


img_gamma = Converters.mergeARGB(
    Views.stack(
        op(red).viewDouble(),
        op(green).viewDouble(),
#@ OpService ops
#@ ImgPlus inputData
#@ Double sigma
#@OUTPUT ImgPlus logFiltered
#@OUTPUT ImgPlus thresholded

# Run this tutorial using the C0Z12 image generated in the 'Crop Confocal Series' tutorial.

# To generate the C0Z12 image, do the following:
# Go to 'file>Open Samples>Confocal Series' and make sure confocal-series.tif is the active image and
# run the Crop Confocal Series tutorial.

from net.imglib2.img.display.imagej import ImageJFunctions
from ij import IJ

# create a log kernel
logKernel = ops.create().kernelLog(inputData.numDimensions(), sigma)

logFiltered = ops.filter().convolve(inputData, logKernel)

# otsu threshold and display
thresholded = ops.threshold().otsu(logFiltered)

# convert to imagej1 imageplus so we can run analyze particles
impThresholded = ImageJFunctions.wrap(thresholded, "wrapped")

# convert to mask and analyze particles
IJ.run(impThresholded, "Convert to Mask", "")
IJ.run(impThresholded, "Analyze Particles...", "display add")
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):

	# set calibration
	detectionParameters.setCalibration(inputImp);
	
	# calculate area of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	#cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) 
	cropped=ops.image().crop(inputDataset.getImgPlus() , interval) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	# instantiate the duplicator and the substackmaker classes
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()

	croppedPlus.changes=False
	croppedPlus.close()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	#APlus.show()
	APlus.getProcessor().resetMinAndMax()
	#APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	#BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	#BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	
	labPlus.close()

	fast=True
	
	# threshold the spots from the red channel
	if (fast==False):
		thresholdedred=SpotDetectionGray(red, data, display, ops, "triangle")
		impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	else:
		impthresholdedred=SpotDetection2(redPlus)
	
	# threshold the spots from the brightness channel
	if (fast==False):
		thresholded=SpotDetectionGray(brightness, data, display, ops, "triangle")
		impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	else:
		impthresholded=SpotDetection2(brightnessPlus)
		
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	roim=RoiManager(True)
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.porphyrinRedPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.porphyrinRedPercentage): return False
		else: return True


	roiClone=inputRoi.clone()
	roiClone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, roiClone)

	impthresholded.show()
	
	countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \
		detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity)
	
	uvPoreList=[]
	for roi in roim.getRoisAsArray():
		uvPoreList.append(roi.clone())

	
	#allList=uvPoreList+closedPoresList+openPoresList
	
	# count particles that are porphyrins (red)
	porphyrinList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, isRed)
	# count particles that are visible on uv but not porphyrins
	sebumList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, notRed)

	
	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in uvPoreList]
	
	# draw the ROIs on to the image
	inputImp.getProcessor().setColor(Color.green)
	IJ.run(inputImp, "Line Width...", "line=3");
	inputImp.getProcessor().draw(inputRoi)
	IJ.run(inputImp, "Line Width...", "line=1");
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList]	
	inputImp.updateAndDraw()

	# calculate stats for the UV visible particles
	detectionParameters.setCalibration(APlus)
	statsDictUV=CountParticles.calculateParticleStatsUV(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	totalUVPoreArea=0
	for area in statsDictUV['Areas']:
		totalUVPoreArea=totalUVPoreArea+area
	averageUVPoreArea=totalUVPoreArea/len(statsDictUV['Areas'])

	poreDiameter=0
	for diameter in statsDictUV['Diameters']:
		poreDiameter=poreDiameter+diameter
	poreDiameter=poreDiameter/len(statsDictUV['Diameters'])

	redTotal=0
	for red in statsDictUV['redPercentage']:
		redTotal=redTotal+red
	redAverage=redTotal/len(statsDictUV['redPercentage'])

	statslist=[len(porphyrinList), 100*redAverage];
	statsheader=[Messages.Porphyrins,  Messages.PercentageRedPixels]

	print("Roi Area: "+str(inputRoiArea))
	print("Total Pore Area: "+str(totalUVPoreArea))
	print("Average Pore Area: "+str(averageUVPoreArea))
	print str(len(uvPoreList))+" "+str(len(porphyrinList))+" "+str(len(sebumList))+" "+str(100*totalUVPoreArea/inputRoiArea)+" "+str(100*redAverage)
	print "cp min circularity"+str(detectionParameters.closedPoresMinCircularity)+":"+str(detectionParameters.closedPoresMinSize)

	# close the thresholded image
	impthresholded.changes=False
	impthresholded.close()
	
	return uvPoreList, statslist, statsheader
Example #28
0
    def run(self):
        for filename in self.filenames:
            try:
                img = self.klb.readFull(os.path.join(srcDir, filename))
                computeInto(maximum(self.aimg, img), self.aimg)
            except:
                syncPrint("Skipping failed image: %s\n%s" %
                          (filename, sys.exc_info()))


# Step 2: project the 4D series into a single 3D image using the maximum function
# (Will read it if it already exists)
max_projection_path = os.path.join(tgtDir, "max_projection.zip")
if os.path.exists(max_projection_path):
    max_projection = IL.wrap(readIJ(max_projection_path))
    print "Loaded max_projection.zip file from disk at", max_projection_path
else:
    # Project the time dimension so that 4D -> 3D
    # Take the median
    sums.sort(key=itemgetter(1))
    median = sums[len(sums) / 2][1]
    max_sum = sums[-1][1]  # last

    print median, max_sum

    # Turns out the maximum is infinity.
    # Therefore, discard all infinity values, and also any above 1.5 * median
    threshold = median * 1.5

    filtered = [
def run(imp, preprocessor_path, postprocessor_path, threshold_method, user_comment):

    output_parameters = {"image title" : "",
    "preprocessor path" : float,
    "post processor path" : float,
    "thresholding op" : float,
    "use ridge detection" : bool,
    "high contrast" : int,
    "low contrast" : int,
    "line width" : int,
    "minimum line length" : int,
    "mitochondrial footprint" : float,
    "branch length mean" : float,
    "branch length median" : float,
    "branch length stdevp" : float,
    "summed branch lengths mean" : float,
    "summed branch lengths median" : float,
    "summed branch lengths stdevp" : float,
    "network branches mean" : float,
    "network branches median" : float,
    "network branches stdevp" : float}

    output_order = ["image title",
    "preprocessor path",
    "post processor path",
    "thresholding op",
    "use ridge detection",
    "high contrast",
    "low contrast",
    "line width",
    "minimum line length",
    "mitochondrial footprint",
    "branch length mean",
    "branch length median",
    "branch length stdevp",
    "summed branch lengths mean",
    "summed branch lengths median",
    "summed branch lengths stdevp",
    "network branches mean",
    "network branches median",
    "network branches stdevp"]

    # Perform any preprocessing steps...
    status.showStatus("Preprocessing image...")
    if preprocessor_path != None:
        if preprocessor_path.exists():
            preprocessor_thread = scripts.run(preprocessor_path, True)
            preprocessor_thread.get()
            imp = WindowManager.getCurrentImage()
    else:
        pass

    # Store all of the analysis parameters in the table
    if preprocessor_path == None:
        preprocessor_str = ""
    else:
        preprocessor_str = preprocessor_path.getCanonicalPath()
    if postprocessor_path == None:
        postprocessor_str = ""
    else:
        postprocessor_str = preprocessor_path.getCanonicalPath()

    output_parameters["preprocessor path"] = preprocessor_str
    output_parameters["post processor path"] = postprocessor_str
    output_parameters["thresholding op"] = threshold_method
    output_parameters["use ridge detection"] = str(use_ridge_detection)
    output_parameters["high contrast"] = rd_max
    output_parameters["low contrast"] = rd_min
    output_parameters["line width"] = rd_width
    output_parameters["minimum line length"] = rd_length

    # Create and ImgPlus copy of the ImagePlus for thresholding with ops...
    status.showStatus("Determining threshold level...")
    imp_title = imp.getTitle()
    slices = imp.getNSlices()
    frames = imp.getNFrames()
    output_parameters["image title"] = imp_title
    imp_calibration = imp.getCalibration()
    imp_channel = Duplicator().run(imp, imp.getChannel(), imp.getChannel(), 1, slices, 1, frames)
    img = ImageJFunctions.wrap(imp_channel)

    # Determine the threshold value if not manual...
    binary_img = ops.run("threshold.%s"%threshold_method, img)
    binary = ImageJFunctions.wrap(binary_img, 'binary')
    binary.setCalibration(imp_calibration)
    binary.setDimensions(1, slices, 1)

    # Get the total_area
    if binary.getNSlices() == 1:
        area = binary.getStatistics(Measurements.AREA).area
        area_fraction = binary.getStatistics(Measurements.AREA_FRACTION).areaFraction
        output_parameters["mitochondrial footprint"] =  area * area_fraction / 100.0
    else:
        mito_footprint = 0.0
        for slice in range(binary.getNSlices()):
            	binary.setSliceWithoutUpdate(slice)
                area = binary.getStatistics(Measurements.AREA).area
                area_fraction = binary.getStatistics(Measurements.AREA_FRACTION).areaFraction
                mito_footprint += area * area_fraction / 100.0
        output_parameters["mitochondrial footprint"] = mito_footprint * imp_calibration.pixelDepth

    # Generate skeleton from masked binary ...
    # Generate ridges first if using Ridge Detection
    if use_ridge_detection and (imp.getNSlices() == 1):
        skeleton = ridge_detect(imp, rd_max, rd_min, rd_width, rd_length)
    else:
        skeleton = Duplicator().run(binary)
        IJ.run(skeleton, "Skeletonize (2D/3D)", "")

    # Analyze the skeleton...
    status.showStatus("Setting up skeleton analysis...")
    skel = AnalyzeSkeleton_()
    skel.setup("", skeleton)
    status.showStatus("Analyzing skeleton...")
    skel_result = skel.run()

    status.showStatus("Computing graph based parameters...")
    branch_lengths = []
    summed_lengths = []
    graphs = skel_result.getGraph()

    for graph in graphs:
        summed_length = 0.0
        edges = graph.getEdges()
        for edge in edges:
            length = edge.getLength()
            branch_lengths.append(length)
            summed_length += length
        summed_lengths.append(summed_length)

    output_parameters["branch length mean"] = eztables.statistical.average(branch_lengths)
    output_parameters["branch length median"] = eztables.statistical.median(branch_lengths)
    output_parameters["branch length stdevp"] = eztables.statistical.stdevp(branch_lengths)

    output_parameters["summed branch lengths mean"] = eztables.statistical.average(summed_lengths)
    output_parameters["summed branch lengths median"] = eztables.statistical.median(summed_lengths)
    output_parameters["summed branch lengths stdevp"] = eztables.statistical.stdevp(summed_lengths)

    branches = list(skel_result.getBranches())
    output_parameters["network branches mean"] = eztables.statistical.average(branches)
    output_parameters["network branches median"] = eztables.statistical.median(branches)
    output_parameters["network branches stdevp"] = eztables.statistical.stdevp(branches)

    # Create/append results to a ResultsTable...
    status.showStatus("Display results...")
    if "Mito Morphology" in list(WindowManager.getNonImageTitles()):
        rt = WindowManager.getWindow("Mito Morphology").getTextPanel().getOrCreateResultsTable()
    else:
        rt = ResultsTable()

    rt.incrementCounter()
    for key in output_order:
        rt.addValue(key, str(output_parameters[key]))

    # Add user comments intelligently
    if user_comment != None and user_comment != "":
        if "=" in user_comment:
            comments = user_comment.split(",")
            for comment in comments:
                rt.addValue(comment.split("=")[0], comment.split("=")[1])
        else:
            rt.addValue("Comment", user_comment)

    rt.show("Mito Morphology")

	# Create overlays on the original ImagePlus and display them if 2D...
    if imp.getNSlices() == 1:
        status.showStatus("Generate overlays...")
        IJ.run(skeleton, "Green", "")
        IJ.run(binary, "Magenta", "")

        skeleton_ROI = ImageRoi(0,0,skeleton.getProcessor())
        skeleton_ROI.setZeroTransparent(True)
        skeleton_ROI.setOpacity(1.0)
        binary_ROI = ImageRoi(0,0,binary.getProcessor())
        binary_ROI.setZeroTransparent(True)
        binary_ROI.setOpacity(0.25)

        overlay = Overlay()
        overlay.add(binary_ROI)
        overlay.add(skeleton_ROI)

        imp.setOverlay(overlay)
        imp.updateAndDraw()

    # Generate a 3D model if a stack
    if imp.getNSlices() > 1:

        univ = Image3DUniverse()
        univ.show()

        pixelWidth = imp_calibration.pixelWidth
        pixelHeight = imp_calibration.pixelHeight
        pixelDepth = imp_calibration.pixelDepth

        # Add end points in yellow
        end_points = skel_result.getListOfEndPoints()
        end_point_list = []
        for p in end_points:
            end_point_list.append(Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth))
        univ.addIcospheres(end_point_list, Color3f(255.0, 255.0, 0.0), 2, 1*pixelDepth, "endpoints")

        # Add junctions in magenta
        junctions = skel_result.getListOfJunctionVoxels()
        junction_list = []
        for p in junctions:
            junction_list.append(Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth))
        univ.addIcospheres(junction_list, Color3f(255.0, 0.0, 255.0), 2, 1*pixelDepth, "junctions")

        # Add the lines in green
        graphs = skel_result.getGraph()
        for graph in range(len(graphs)):
            edges = graphs[graph].getEdges()
            for edge in range(len(edges)):
                branch_points = []
                for p in edges[edge].getSlabs():
                    branch_points.append(Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth))
                univ.addLineMesh(branch_points, Color3f(0.0, 255.0, 0.0), "branch-%s-%s"%(graph, edge), True)

        # Add the surface
        univ.addMesh(binary)
        univ.getContent("binary").setTransparency(0.5)

    # Perform any postprocessing steps...
    status.showStatus("Running postprocessing...")
    if postprocessor_path != None:
        if postprocessor_path.exists():
            postprocessor_thread = scripts.run(postprocessor_path, True)
            postprocessor_thread.get()

    else:
        pass

    status.showStatus("Done analysis!")
from ij import ImagePlus
from ij.plugin.filter import BackgroundSubtracter

from jarray import array

from fiji.plugin.trackmate.detection import DetectionUtils

from net.imagej.ops.convert import ConvertPixCopy

###############################################################
# Step 1:  Rolling ball background subtraction (still uses IJ1)
###############################################################

# wrap as ImagePlus
imp=ImageJFunctions.wrap(inputData, "wrapped")

# create and call background subtractor
bgs=BackgroundSubtracter()
bgs.rollingBallBackground(imp.getProcessor(), 50.0, False, False, True, True, True) 

# wrap the result of background subtraction as Img
iplus=ImagePlus("bgs", imp.getProcessor())
imgBgs=ImageJFunctions.wrapShort(iplus)


###############################################################
# Step 2:  Laplacian of Gaussian Filtering
###############################################################

# convert to 32 bit
    results.incrementCounter()
    results.addValue("area", area.getRealDouble())
    results.addValue("min", min.getRealDouble())
    results.addValue("max", max.getRealDouble())
    results.addValue("mean", mean.getRealDouble())
    results.addValue("median", median.getRealDouble())
    results.addValue("stdev", stdev.getRealDouble())
    results.addValue("sum", sum.getRealDouble())
    results.addValue("comment", comment)

# Display the table
results.show("Results")

# Outline and highlight the regions
outline = ops.run("morphology.outline", binary, False)
image_imp = ImageJFunctions.wrap(image, "Overlay Render")
binary_imp = ImageJFunctions.wrap(binary, "Binary")
outline_imp = ImageJFunctions.wrap(outline, "Outline")

IJ.run(binary_imp, "Green", "")
binary_ROI = ImageRoi(0, 0, binary_imp.getProcessor())
binary_ROI.setZeroTransparent(True)
binary_ROI.setOpacity(0.25)

IJ.run(outline_imp, "Green", "")
outline_ROI = ImageRoi(0, 0, outline_imp.getProcessor())
outline_ROI.setZeroTransparent(True)
outline_ROI.setOpacity(1.00)

overlay = Overlay()
overlay.add(binary_ROI)
        categorizer = CategorizerWithState.generateFixedRange( ranges )

        categorizer = RangedCategorizer( nImages )

        matrices    = DenseCorrelationMatricesWithRadius(
			wrappedImage,
			radii[0],
			c,
			DoubleType()
			)
        
        result = MultiScaleEstimation.estimateZCoordinates( matrices, startingCoordinates, c, radii, steps, visitor, categorizer, opt )
        IJ.log("done")

        resultFileName = '%s/result.tif' % home.rstrip('/')
        imp = ImageJFunctions.wrap( result, 'result' )
        IJ.saveAsTiff(imp.duplicate(), resultFileName)

        relativeResult = result.copy()
        c = relativeResult.cursor()
        while c.hasNext():
            c.fwd()
            cur = c.get()
            val = cur.get()
            cur.set( val - c.getDoublePosition( 2 ) )

        relativeResultFileName = '%s/relativeResult.tif' % home.rstrip('/')
        imp = ImageJFunctions.wrap( relativeResult, 'relative result' )
        IJ.saveAsTiff(imp.duplicate(), relativeResultFileName)

        ratio = [ wrappedImage.dimension( 0 )*1.0/result.dimension( 0 ), wrappedImage.dimension( 1 )*1.0/result.dimension( 1 ) ]
# @DisplayService display
# @OpService ops
# @net.imagej.Dataset inputData

from net.imglib2.meta import ImgPlus
from net.imglib2.img.display.imagej import ImageJFunctions

from jarray import array
from ij import IJ

# create a log kernel
logKernel=ops.logKernel(inputData.numDimensions(), 1.0);

# convolve with log kernel
logFiltered=ops.convolve(inputData, logKernel);

# display log filter result
display.createDisplay("log", ImgPlus(logFiltered));

# otsu threshold and display
thresholded = ops.run("threshold.otsu",logFiltered)
display.createDisplay("thresholded", ImgPlus(thresholded));

# convert to imagej1 imageplus so we can run analyze particles
impThresholded=ImageJFunctions.wrap(thresholded, "wrapped")

# convert to mask and analyze particles
IJ.run(impThresholded, "Convert to Mask", "")
IJ.run(impThresholded, "Analyze Particles...", "display add");
IJ.run("Close");
Example #34
0
    stack_slice = ArrayImgFactory(
        img.randomAccess().get().createVariable()).create(
            [canvas_width, canvas_height])
    target = Views.interval(
        stack_slice, [xOffset, yOffset],
        [xOffset + img.dimension(0) - 1, yOffset + img.dimension(1) - 1])
    c1 = target.cursor()
    c2 = img.cursor()
    while c1.hasNext():
        c1.next().set(c2.next())

    return stack_slice


# Re-cut ROIs, this time in RGB rather than just red
img1 = Views.interval(img, [r1.x, r1.y],
                      [r1.x + r1.width - 1, r1.y + r1.height - 1])
img2 = Views.interval(img, [r2.x, r2.y],
                      [r2.x + r2.width - 1, r2.y + r2.height - 1])

# Insert each into a stack slice
xOffset1 = 0 if dx >= 0 else abs(dx)
yOffset1 = 0 if dy >= 0 else abs(dy)
xOffset2 = 0 if dx <= 0 else dx
yOffset2 = 0 if dy <= 0 else dy
slice1 = intoSlice(img1, xOffset1, yOffset1)
slice2 = intoSlice(img2, xOffset2, yOffset2)

stack = Views.stack([slice1, slice2])
IL.wrap(stack, "registered with phase correlation").show()
Example #35
0
# This is not indexed by intellij
import net.imagej.legacy.IJ1Helper
import org.scijava.log.LogService

from net.imglib2.img.display.imagej import ImageJFunctions
# log = IJ1Helper.getLegacyContext().getService(LogService.class)

# Finds methods but no signatures
from ij import IJ
IJ.open()

repurl = "http://imagej.net/images"

IJ.open(repurl + "/FluorescentCells.jpg")
imp = IJ.getImage()
print imp.getClass()

img = ImageJFunctions.wrap(imp)
print img.getClass()
  if title.startswith("Energy"):
  	# Keep "Energy"
	energyImp = impOpened;

### Remove holes from image ###
# Selection mask from overlay
manualMask = maskFromOverlay(imp);

# Invert
invertedManualMask = invertImg(manualMask);

if IJ.debugMode:
  displays.createDisplay("manual-mask", ImgPlus(invertedManualMask));

# Threshold energyImp
wrappedImg = ImageJFunctions.wrap(energyImp);
if useEnergy:
  energyMask = ops.create().img(wrappedImg, BitType());
  ops.threshold().apply(energyMask, wrappedImg, FloatType(0.20));
  
  # Invert, b/c we want to have lower energy regions
  #invertedOutput = invertImg(output);
  
  if IJ.debugMode:
    displays.createDisplay("energy-mask", ImgPlus(energyMask));

# Convert mask to binary image
wrappedManualMask = ImageJFunctions.wrap(maskImp);
coherencyMask = ops.create().img(wrappedImg, BitType());
ops.convert().bit(coherencyMask, wrappedManualMask);
Example #37
0
    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()


path = "/net/ark/raw/fibsem/pygmy-squid/2021-12_popeye/Popeye2/Y2021/M12/D23/FIBdeSEMAna_21-12-23_235849_0-0-0.dat"


channels = readFIBSEMdat(path)
print channels
IL.wrap(channels[0], "channel 1").show() # looks good
IL.wrap(channels[1], "channel 2").show() # looks grainy, lots of shot noise
                                                                                                       


    imgSource.getProcessor().multiply( 1.0 / normalizeBy )
    nThreads = 1
    serializeCorrelations = True
    deserializeCorrelations = not serializeCorrelations
    options = Options.generateDefaultOptions()
    options.shiftProportion = 0.6
    options.nIterations = 30
    options.withRegularization = True
    options.minimumSectionThickness = 0.0001
    options.multiplierGenerationRegularizerWeight = 0.1
    options.multiplierEstimationIterations = 10
    options.withReorder = False
    options.coordinateUpdateRegularizerWeight = 0.0
    thickness_estimation_repo_dir = '/groups/saalfeld/home/hanslovskyp/workspace/em-thickness-estimation'

    wholeStrip = ImageJFunctions.wrap( imgSource )

    timestamp  = str(datetime.datetime.now() )

    threads = []
    upper = start
    while upper < stop:
        correlationRange = int(c)
        lower            = max( 0, upper - overlap )
        upper            = lower + interval
        if upper + step >= stop:
            upper = min( stop, upper + step )
        
        home = root.rstrip('/') + '/range=%d_%s/lower=%d_upper=%d'
        home = home % ( correlationRange, timestamp, lower, upper )
        make_sure_path_exists( home.rstrip('/') + '/' )
Example #39
0
toCenter.setTranslation(-cx, -cy, 0.0)  # no translation in the Z axis
rotation = AffineTransform3D()
# Step 1: place origin of rotation at the center of the image
rotation.preConcatenate(toCenter)
# Step 2: rotate around the Z axis
rotation.rotate(2, angle)  # 2 is the Z axis, or 3rd dimension
# Step 3: undo translation to the center
rotation.preConcatenate(toCenter.inverse())  # undo translation to the center

# Define a rotated view of the image
rotated = RV.transform(imgR, rotation)

# View the image rotated, without enlarging the canvas
# so we define the interval (here, the field of view of an otherwise infinite image)
# as the original image dimensions by using "img", which in itself is an Interval.
imgRot2d = IL.wrap(Views.interval(rotated, img), imp.getTitle() + " - rot2d")
imgRot2d.show()

# View the image rotated, enlarging the interval to fit it.
# (This is akin to enlarging the canvas.)

# We define each corner of the nth-dimensional volume as a combination,
# namely the 'product' (think nested loop) of the pairs of possible values
# that each dimension can take in every corner coordinate, zipping each
# with the value zero (hence the repeat(0) to provide as many as necessary),
# and then unpacking the list of pairs by using the * in front of 'zip'
# so that 'product' receives the pairs as arguments rather than a list of pairs.
# Then we apply the transform to each corner, reading out the transformed coordinates
# by using the 'transformed' float array.

# We compute the bounds by, for every corner, checking if the floor of each dimension
rm = RoiManager.getInstance()
if not rm:
    rm = RoiManager()
rm.runCommand("reset")

#ask the user to define a selection and get the bounds of the selection
IJ.setTool(Toolbar.RECTANGLE)
WaitForUserDialog("Select the area,then click OK.").show()
boundRect = imp.getRoi()
imp.setRoi(boundRect)
rm.addRoi(boundRect)

imp = IJ.getImage()
cal = imp.getCalibration()  # in microns

img = IJF.wrap(imp)

print(img.dimensions)
# Create a variable of the correct type (UnsignedByteType) for the value-extended view
zero = img.randomAccess().get().createVariable()

# Run the difference of Gaussian
cell = 30.0  # microns in diameter
min_peak = 10.0  # min intensity for a peak to be considered
dog = DogDetection(
    Views.extendValue(img, zero),
    img,
    [cal.pixelWidth, cal.pixelHeight],
    cell / 2,
    cell,
    DogDetection.ExtremaType.MAXIMA,  #MAXIMA