def translate_single_stack_using_imglib2(imp, dx, dy, dz):
  # wrap into a float imglib2 and translate
  #   conversion into float is necessary due to "overflow of n-linear interpolation due to accuracy limits of unsigned bytes"
  #   see: https://github.com/fiji/fiji/issues/136#issuecomment-173831951
  img = ImagePlusImgs.from(imp.duplicate())
  extended = Views.extendBorder(img)
  converted = Converters.convert(extended, RealFloatSamplerConverter())
  interpolant = Views.interpolate(converted, NLinearInterpolatorFactory())
  
  # translate
  if imp.getNDimensions()==3:
    transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz))
  elif imp.getNDimensions()==2:
    transformed = RealViews.affine(interpolant, Translation2D(dx, dy))
  else:
    IJ.log("Can only work on 2D or 3D stacks")
    return None
  
  cropped = Views.interval(transformed, img)
  # wrap back into bit depth of input image and return
  bd = imp.getBitDepth()
  if bd==8:
    return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2"))
  elif bd == 16:
    return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2"))
  elif bd == 32:
    return(ImageJFunctions.wrapFloat(cropped,"imglib2"))
  else:
    return None    
示例#2
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()
示例#3
0
def translate_single_stack_using_imglib2(imp, dx, dy, dz):
  # wrap into a float imglib2 and translate
  #   conversion into float is necessary due to "overflow of n-linear interpolation due to accuracy limits of unsigned bytes"
  #   see: https://github.com/fiji/fiji/issues/136#issuecomment-173831951
  img = ImagePlusImgs.from(imp.duplicate())
  extended = Views.extendZero(img)
  converted = Converters.convert(extended, RealFloatSamplerConverter())
  interpolant = Views.interpolate(converted, NLinearInterpolatorFactory())
  
  # translate
  if imp.getNDimensions()==3:
    transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz))
  elif imp.getNDimensions()==2:
    transformed = RealViews.affine(interpolant, Translation2D(dx, dy))
  else:
    IJ.log("Can only work on 2D or 3D stacks")
    return None
  
  cropped = Views.interval(transformed, img)
  # wrap back into bit depth of input image and return
  bd = imp.getBitDepth()
  if bd==8:
    return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2"))
  elif bd == 16:
    return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2"))
  elif bd == 32:
    return(ImageJFunctions.wrapFloat(cropped,"imglib2"))
  else:
    return None    
示例#4
0
def find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue):
	# FIND PEAKS
	# sigmaSmaller ==> Size of the smaller dots (in pixels)
	# sigmaLarger ==> Size of the bigger dots (in pixels)
	# minPeakValue ==> Intensity above which to look for dots
	# Preparation Neuron channel
	ip1_1 = IL.wrapReal(imp1)
	ip1E = Views.extendMirrorSingle(ip1_1)
	imp1.show()

	#Preparation Glioma channel
	ip2_1 = IL.wrapReal(imp2)
	ip2E = Views.extendMirrorSingle(ip2_1)
	imp2.show()

	calibration = [1.0 for i in range(ip1_1.numDimensions())]
	extremaType = DogDetection.ExtremaType.MINIMA
	normalizedMinPeakValue = False

	dog_1 = DogDetection(ip1E, ip1_1, calibration, sigmaSmaller, sigmaLarger,
	  				   extremaType, minPeakValue, normalizedMinPeakValue)

	dog_2 = DogDetection(ip2E, ip2_1, calibration, sigmaSmaller, sigmaLarger,
	  				   extremaType, minPeakValue, normalizedMinPeakValue)

	peaks_1 = dog_1.getPeaks()
	peaks_2 = dog_2.getPeaks()

	return ip1_1, ip2_1, peaks_1, peaks_2
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)
示例#6
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))
示例#7
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))
def getFFTParamsFromImps(imp1, imp2, r1=None, r2=None):
    if r1:
        v1 = getViewFromImp(imp1, r1)
    else:
        v1 = IL.wrapByte(imp1)
    if r2:
        v2 = getViewFromImp(imp2, r2)
    else:
        v2 = IL.wrapByte(imp2)

    extension = array(v1.numDimensions() * [10], 'i')
    extSize = PhaseCorrelation2Util.getExtendedSize(v1, v2, extension)
    paddedDimensions = array(extSize.numDimensions() * [0], 'l')
    fftSize = array(extSize.numDimensions() * [0], 'l')
    return extension, extSize, paddedDimensions, fftSize
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
 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))
示例#11
0
文件: ui.py 项目: acardona/scripts
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 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 getViewFromImp(imp, r=None):
    # r is a java.awt.rectangle
    im = IL.wrapByte(imp)
    if r is None:
        r = Rectangle(0, 0, imp.getWidth(), imp.getHeight())
    v = Views.zeroMin(
        Views.interval(im, [r.x, r.y],
                       [r.x + r.width - 1, r.y + r.height - 1]))
    return v
示例#15
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 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()
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 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 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)
示例#20
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 translate_using_imglib2(imp, dx, dy, dz):
  print "imp channels",imp.getNChannels()
  # todo:
  # if multiple channels use Duplicator to translate each channel individually
  ## wrap
  # http://javadoc.imagej.net/ImgLib2/net/imglib2/img/imageplus/ImagePlusImg.html
  img = ImagePlusImgs.from(imp.duplicate())
  print "dimensions:",img.numDimensions()
  print img.getChannels()
  ## prepare image
  print "img",img
  ddd
  extended = Views.extendBorder(img)
  #print "extended",extended
  #print "extended",extended.dimension(1)
  dims = zeros(4, 'l')
  img.dimensions(dims)
  print "dims",dims
  converted = Converters.convert(extended, RealFloatSamplerConverter())
  composite = Views.collapseReal(converted, imp.getNChannels())
  print "composite",composite
  interpolant = Views.interpolate(composite, NLinearInterpolatorFactory())
  #print "interpolant",interpolant
  transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz))
  print "transformed", transformed
  cropped = Views.interval(transformed, img)
  print "cropped.numDimensions()", cropped.numDimensions()
  print "cropped",cropped
  ## wrap back and return
  bd = imp.getBitDepth()
  # maybe simply wrap works?
  if bd==8:
    return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2"))
  elif bd == 16:
    return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2"))
  elif bd == 32:
    return(ImageJFunctions.wrapFloat(cropped,"imglib2"))
  else:
    return None    
示例#22
0
文件: ui.py 项目: acardona/scripts
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
示例#23
0
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;
示例#25
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)))
示例#27
0
文件: ui.py 项目: acardona/scripts
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)
示例#28
0
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 )


# @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");
示例#30
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)
示例#31
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)
#@ 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")
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
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!")
        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 ) ]
  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);
def poreDetectionTrueColor(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	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(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)

	# separate into RGB and get the blue channel
	IJ.run(duplicate, "RGB Stack", "")
	bluePlus=substackMaker.makeSubstack(duplicate, "3-3")
	blue=ImgPlus(ImageJFunctions.wrapByte(bluePlus))
	bluePlus.setTitle("Blue")
	
	# duplicate and look for bright spots
	thresholdedLight=SpotDetection2(bluePlus)

	# duplicate and look for dark spots
	thresholdedDark=SpotDetection3(bluePlus, True)

	# convert to mask
	Prefs.blackBackground = True
	#IJ.run(thresholdedDark, "Convert to Mask", "")substackMaker

	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(thresholdedLight, clone)
	Utility.clearOutsideRoi(thresholdedDark, clone)
	roimClosedPores = RoiManager(True)
	detectionParameters.setCalibration(thresholdedDark)
	countParticles(thresholdedDark, roimClosedPores, detectionParameters.closedPoresMinSize, detectionParameters.closedPoresMaxSize, \
		detectionParameters.closedPoresMinCircularity, detectionParameters.closedPoresMaxCircularity)

	# count number of open pores
	roimOpenPores = RoiManager(True)
	detectionParameters.setCalibration(thresholdedDark)
	countParticles(thresholdedDark, roimOpenPores, detectionParameters.openPoresMinSize, detectionParameters.openPoresMaxSize, \
		detectionParameters.openPoresMinCircularity, detectionParameters.openPoresMaxCircularity)

	# count number of sebum
	roimSebum = RoiManager(True)
	detectionParameters.setCalibration(thresholdedLight)
	countParticles(thresholdedLight, roimSebum, detectionParameters.sebumMinSize, detectionParameters.sebumMaxSize, \
		detectionParameters.sebumMinCircularity, detectionParameters.sebumMaxCircularity)
	
	# create lists for open and closed pores
	closedPoresList=[]
	for roi in roimClosedPores.getRoisAsArray():
		closedPoresList.append(roi.clone())
	openPoresList=[]
	for roi in roimOpenPores.getRoisAsArray():
		openPoresList.append(roi.clone())

	# create lists for sebum
	sebumsList=[]
	for roi in roimSebum.getRoisAsArray():
		sebumsList.append(roi.clone())

	# a list of all pores
	allList=closedPoresList+openPoresList+sebumsList
	
	# calculate the stats for all pores
	detectionParameters.setCalibration(bluePlus)
	statsDict=CountParticles.calculateParticleStats(bluePlus, allList)

	poresTotalArea=0
	for area in statsDict['Areas']:
		poresTotalArea=poresTotalArea+area
		print area
	poresAverageArea=poresTotalArea/len(statsDict['Areas'])
		

	# 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]
	
	# draw the rois on 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.red) for roi in closedPoresList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in openPoresList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumsList]
	
	inputImp.updateAndDraw()
	
	# close images that represent intermediate steps
	croppedPlus.changes=False
	croppedPlus.close()
	bluePlus.changes=False
	bluePlus.close()

	print "Total ROI Area: "+str(inputRoiArea)
	print "Num closed pores: "+str(len(closedPoresList))
	print "Num open pores: "+str(len(openPoresList))
	print "Num sebums: "+str(len(sebumsList))
	
	print "Total particles: "+str(len(allList))+ " total area: "+str(poresTotalArea)
	
	statslist=[inputRoiArea, len(allList), len(closedPoresList), len(openPoresList), len(sebumsList), poresAverageArea, 100*poresTotalArea/inputRoiArea]
	header=[Messages.TotalAreaMask, Messages.TotalDetectedPores, Messages.ClosedPores, Messages.OpenPores, Messages.Sebum, Messages.PoresAverageArea, Messages.PoresFractionalArea]
	
	return header,statslist

	
示例#39
0
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)
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)
示例#41
0
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()
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
示例#43
0
from ij import IJ
from ij.gui import PointRoi
from ij.measure import ResultsTable
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from net.imglib2.view import Views
from net.imglib2.algorithm.dog import DogDetection
from jarray import zeros

# Load a greyscale single-channel image: the "Embryos" sample image
imp = IJ.openImage("https://imagej.nih.gov/ij/images/embryos.jpg")
imp.show()
# Convert it to 8-bit
IJ.run(imp, "8-bit", "")

# Access its pixel data from an ImgLib2 data structure: a RandomAccessibleInterval
img = IL.wrapReal(imp)

# View as an infinite image, mirrored at the edges which is ideal for Gaussians
imgE = Views.extendMirrorSingle(img)

# Parameters for a Difference of Gaussian to detect embryo positions
calibration = [1.0
               for i in range(img.numDimensions())]  # no calibration: identity
sigmaSmaller = 15  # in pixels: a quarter of the radius of an embryo
sigmaLarger = 30  # pixels: half the radius of an embryo
extremaType = DogDetection.ExtremaType.MAXIMA
minPeakValue = 10
normalizedMinPeakValue = False

# In the differece of gaussian peak detection, the img acts as the interval
# within which to look for peaks. The processing is done on the infinite imgE.
    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('/') + '/' )
示例#45
0
from net.imglib2.realtransform import RealViews as RV
from net.imglib2.realtransform import AffineTransform3D
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from ij import IJ
from net.imglib2.view import Views
from net.imglib2.interpolation.randomaccess import NLinearInterpolatorFactory
from net.imglib2.util import Intervals
from math import radians, floor, ceil
from jarray import zeros
from pprint import pprint

# Load an image (of any dimensions)
imp = IJ.getImage()

# Access its pixel data as an ImgLib2 RandomAccessibleInterval
img = IL.wrapReal(imp)

# View as an infinite image, with value zero beyond the image edges
imgE = Views.extendZero(img)

# View the pixel data as a RealRandomAccessible
# (that is, accessible with sub-pixel precision)
# by using an interpolator
imgR = Views.interpolate(imgE, NLinearInterpolatorFactory())

# Define a rotation by +30 degrees relative to the image center in the XY axes
angle = radians(30)
toCenter = AffineTransform3D()
cx = img.dimension(0) / 2.0  # X axis
cy = img.dimension(1) / 2.0  # Y axis
toCenter.setTranslation(-cx, -cy, 0.0)  # no translation in the Z axis
# wrap as ImagePlus
imp=IJ.getImage()
#imp=ImageJFunctions.wrap(blue, "wrapped")

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

imp.getProcessor().invert()
imp.show()

print imp

# wrap as Img and display
iplus=ImagePlus("bgs", imp.getProcessor())
imgBgs=ImageJFunctions.wrapByte(iplus)
print iplus
print imgBgs

display.createDisplay("back_sub", data.create(ImgPlus(imgBgs))) 

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

print type(kernel)
print type(imgBgs)

bgs32=ImgPlus( ops.create( dimensions2D, FloatType()) )
ops.convert(bgs32, imgBgs, ConvertPixCopy() )

log = ops.convolve(ops.create( dimensions2D, FloatType()), bgs32, kernel)