示例#1
0
def setChannelInvisible(project,channel):
	layerset = project.getRootLayerSet()
	layers = layerset.getLayers()
	for l,layer in enumerate(layers):
		patches = layer.getDisplayables(Patch)
		for patch in patches:
			patchName = nameFromPath(patch.getImageFilePath())
			if patchName[0:len(channel)] == channel:
				patch.setVisible(False, True)
			Display.getFront().updateVisibleTabs()
示例#2
0
def toggleChannel(project,channel):
	layerset = project.getRootLayerSet()
	layers = layerset.getLayers()
	for l,layer in enumerate(layers):
		patches = layer.getDisplayables(Patch)
		for patch in patches:
			# IJ.log('thepatch' + str(patch))
			patchName = nameFromPath(patch.getImageFilePath())
			# IJ.log(str(patchName[0:len(channel)]) + '=' + str(channel) + ' value' + str(patchName[0:len(channel)] == channel) )
			if patchName[0:len(channel)] == channel:
				# IJ.log(str(patch) + ' toggled')
				patch.setVisible((not patch.visible), True)
				Display.getFront().updateVisibleTabs()
示例#3
0
def setChannelVisible(project,channel):
	layerset = project.getRootLayerSet()
	layers = layerset.getLayers()
	for l,layer in enumerate(layers):
		patches = layer.getDisplayables(Patch)
		for patch in patches:
			patchName = nameFromPath(patch.getImageFilePath())
			if patchName[0:len(channel)] == channel:
				patch.setVisible(True, True)
			# else:
				# patch.setVisible(False, True)
		try:
			Display.getFront().updateVisibleTabs()
		except Exception, e:
			IJ.log('Did not succeed in updating the visible tabs')
			pass
示例#4
0
def exportSegmentation(evt=None):
  display = Display.getFront()
  canvas = display.getCanvas()
  numLayer = display.getLayerSet().size();

  exportMask(evt)
  
  files = []
  for l in display.getLayerSet().getLayers():
    for p in l.getDisplayables(Patch):
      files.append(p.getFilePath())
  # Create virtual stack 'vs'
  vs = None
  for f in files:
    # if first image...
    if vs is None:
      imp = IJ.openImage(f)
      vs = VirtualStack(imp.width, imp.height, None, "/")
    vs.addSlice(f)
  ImagePlus("VSeg", vs).show()
  IJ.run("Duplicate...", "title=Segmentation duplicate range=1-30");
  WindowManager.getImage("VSeg").close()
  ic = ImageCalculator()
  ic.run("Multiply stack", WindowManager.getImage("Segmentation"), WindowManager.getImage("Labels"));
  WindowManager.getImage("Labels").close()
示例#5
0
def profileDistances(ID, biniter):

  histo=getDendriticProfiles(ID, biniter)

  xhisto=histo[0]
  yhisto=histo[1]
  zhisto=histo[2]

  xdistance=[]
  ydistance=[]
  zdistance=[]

  tree = Display.getFront().getLayerSet().findById(ID)
  coords = Matrix(getNodeCoordinates(tree))
  m=coords.getRowDimension()

  for i in range(0, m):
    xdist = coords.get(i, 1 )
    if xdist > 0 :
      xdistance.append(xdist)
    else:
      xdistance.append((-1)*xdist)

  for i in range(0, m):
    ydist = coords.get(i, 0 )
    if ydist > 0 :
      ydistance.append(ydist)
    else:
      ydistance.append((-1)*ydist)

  for i in range(0, m):
    zdist = sqrt(coords.get(i, 0)**2 + coords.get(i,1)**2)
    zdistance.append(zdist)

  return xdistance, ydistance, zdistance
def getTheTag(tagString):
# find one tag with tagString
    areatrees = Display.getFront().getLayerSet().getZDisplayables(AreaTree)
    connectors = Display.getFront().getLayerSet().getZDisplayables(Connector)
    for tree in itertools.chain(areatrees, connectors):
        root = tree.getRoot()
        if root is None:
            break
        for node in root.getSubtreeNodes():
            tags = node.getTags()
            if tags is None:
                continue
            for tag in tags:
                if tagString in tag.toString():
                    return tag
    return None
示例#7
0
def getBranches(tree):
  tree = Display.getFront().getLayerSet().findById(tree)
  """ Return a list of remaining branch vertices and lists of lists of Point3f, each inner list representing a branch with Point3d. """
  m = tree.asVertices() # map of Node keys vs. Vertex values
  steps = Centrality.branchWise(m.values(), 2)
  branches = []
  for step in steps:
    s = []
    for branch in step.branches:
      nds = [vertex.data for vertex in branch]
      b = []
      for nd in asSequence(nds):
        # transfrom nd to Point3d
        calibration = tree.getLayerSet().getCalibration()
        affine = tree.getAffineTransform()
        fp = array([nd.getX(), nd.getY()], 'f')
        affine.transform(fp, 0, fp, 0, 1)
        x = fp[0] * calibration.pixelWidth
        y = fp[1] * calibration.pixelHeight
        z = nd.getLayer().getZ() * calibration.pixelWidth
        tfm = correct([x, y, z])
        p = Point3d(tfm[0], tfm[1], tfm[2])    #and transform in new coordinates  
        b.append(p)
      s.append(b)
    branches.append([step.remaining_branch_vertices, s])
  return branches
示例#8
0
def getTheTag(tagString):
    # find one tag with tagString
    areatrees = Display.getFront().getLayerSet().getZDisplayables(AreaTree)
    connectors = Display.getFront().getLayerSet().getZDisplayables(Connector)
    for tree in itertools.chain(areatrees, connectors):
        root = tree.getRoot()
        if root is None:
            break
        for node in root.getSubtreeNodes():
            tags = node.getTags()
            if tags is None:
                continue
            for tag in tags:
                if tagString in tag.toString():
                    return tag
    return None
示例#9
0
def extract_stack_under_arealist():
    # Check that a Display is open
    display = Display.getFront()
    if display is None:
        IJ.log("Open a TrakEM2 Display first!")
        return
    # Check that an AreaList is selected and active:
    ali = display.getActive()
    if ali is None or not isinstance(ali, AreaList):
        IJ.log("Please select an AreaList first!")
        return

    # Get the range of layers to which ali paints:
    ls = display.getLayerSet()
    ifirst = ls.indexOf(ali.getFirstLayer())
    ilast = ls.indexOf(ali.getLastLayer())
    layers = display.getLayerSet().getLayers().subList(ifirst, ilast + 1)

    # Create a stack with the dimensions of ali
    bounds = ali.getBoundingBox()
    stack = ImageStack(bounds.width, bounds.height)

    # Using 16-bit. To change to 8-bit, use GRAY8 and ByteProcessor in the two lines below:
    type = ImagePlus.GRAY16
    ref_ip = ShortProcessor(bounds.width, bounds.height)

    for layer in layers:
        area = ali.getArea(layer)
        z = layer.getZ()
        ip = ref_ip.createProcessor(bounds.width, bounds.height)
        if area is None:
            stack.addSlice(str(z), bp)
            continue

        # Create a ROI from the area of ali at layer:
        aff = ali.getAffineTransformCopy()
        aff.translate(-bounds.x, -bounds.y)
        roi = ShapeRoi(area.createTransformedArea(aff))

        # Create a cropped snapshot of the images at layer under ali:
        flat = Patch.makeFlatImage(type, layer, bounds, 1.0,
                                   layer.getDisplayables(Patch), Color.black)
        b = roi.getBounds()
        flat.setRoi(roi)
        ip.insert(flat.crop(), b.x, b.y)

        # Clear the outside of ROI (ShapeRoi is a non-rectangular ROI type)
        bimp = ImagePlus("", ip)
        bimp.setRoi(roi)
        ip.setValue(0)
        ip.setBackgroundValue(0)
        IJ.run(bimp, "Clear Outside", "")

        # Accumulate slices
        stack.addSlice(str(z), ip)

    imp = ImagePlus("AreaList stack", stack)
    imp.setCalibration(ls.getCalibrationCopy())
    imp.show()
def extract_stack_under_arealist():
	# Check that a Display is open
	display = Display.getFront()
	if display is None:
		IJ.log("Open a TrakEM2 Display first!")
		return
	# Check that an AreaList is selected and active:
	ali = display.getActive()
	if ali is None or not isinstance(ali, AreaList):
		IJ.log("Please select an AreaList first!")
		return

	# Get the range of layers to which ali paints:
	ls = display.getLayerSet()
	ifirst = ls.indexOf(ali.getFirstLayer())
	ilast = ls.indexOf(ali.getLastLayer())
	layers = display.getLayerSet().getLayers().subList(ifirst, ilast +1)

	# Create a stack with the dimensions of ali
	bounds = ali.getBoundingBox()
	stack = ImageStack(bounds.width, bounds.height)

	# Using 16-bit. To change to 8-bit, use GRAY8 and ByteProcessor in the two lines below:
	type = ImagePlus.GRAY16
	ref_ip = ShortProcessor(bounds.width, bounds.height)

	for layer in layers:
		area = ali.getArea(layer)
		z = layer.getZ()
		ip = ref_ip.createProcessor(bounds.width, bounds.height)
		if area is None:
			stack.addSlice(str(z), bp)
			continue

		# Create a ROI from the area of ali at layer:
		aff = ali.getAffineTransformCopy()
		aff.translate(-bounds.x, -bounds.y)
		roi = ShapeRoi(area.createTransformedArea(aff))

		# Create a cropped snapshot of the images at layer under ali:
		flat = Patch.makeFlatImage(type, layer, bounds, 1.0, layer.getDisplayables(Patch), Color.black)
		b = roi.getBounds()
		flat.setRoi(roi)
		ip.insert(flat.crop(), b.x, b.y)

		# Clear the outside of ROI (ShapeRoi is a non-rectangular ROI type)
		bimp = ImagePlus("", ip)
		bimp.setRoi(roi)
		ip.setValue(0)
		ip.setBackgroundValue(0)
		IJ.run(bimp, "Clear Outside", "")

		# Accumulate slices
		stack.addSlice(str(z), ip)

	imp = ImagePlus("AreaList stack", stack)
	imp.setCalibration(ls.getCalibrationCopy())
	imp.show()
def run():
  front = Display.getFront()
  if front is None:
    print "No displays open!"
    return
  sel = front.getSelection().getSelected(Profile)
  if sel.isEmpty():
    print "No profiles selected!"
    return
  svg = export(sel.get(0))
  tw = TextWindow("Profile as SVG", svg, 500, 500)
  GUI.center(tw)
示例#12
0
def exportMask(evt=None):
  display = Display.getFront()
  arealists = display.getSelection().getSelected(AreaList)
  canvas = display.getCanvas()
  numLayer = display.getLayerSet().size();
  if arealists.isEmpty():
    IJ.log("No arealists selected -- I just take the FIRST ONE!!")
    #IJ.showMessage("No arealists selected -- select one!")
    zDispList = display.getLayerSet().getDisplayableList()
    if len(zDispList) > 0:
      arealists = zDispList
    else:
      IJ.log("Project does not contain any AreaLists!")
      IJ.showMessage("Project does not contain any AreaLists!")
      return
  AreaList.exportAsLabels(arealists, canvas.getFakeImagePlus().getRoi(), 1.0, 0, numLayer-1, False, False, False);
示例#13
0
def getNodes(tree):
  """Return a list of remaining vertices and lists of lists of all nodes representing a branch"""
  tree = Display.getFront().getLayerSet().findById(tree)
  m = tree.asVertices() # map of Node keys vs. Vertex values
  steps = Centrality.branchWise(m.values(), 2) 
  branches = []
  saveNodes = []
  for step in steps:
    for branch in step.branches:
      b = []
      branchNodes = []
      for vertex in branch:
        nd = vertex.data
        branchNodes.append(nd)
    saveNodes.append([step.remaining_branch_vertices, branchNodes])
  return saveNodes
示例#14
0
def openStack(evt=None):
  display = Display.getFront()
  canvas = display.getCanvas()
  numLayer = display.getLayerSet().size();
  
  files = []
  for l in display.getLayerSet().getLayers():
    for p in l.getDisplayables(Patch):
      files.append(p.getFilePath())
  # Create virtual stack 'vs'
  vs = None
  for f in files:
    # if first image...
    if vs is None:
      imp = IJ.openImage(f)
      vs = VirtualStack(imp.width, imp.height, None, "/")
    vs.addSlice(f)
  layerset = display.getLayerSet()
  p = layerset.getProject()
  ImagePlus("VSeg", vs).show()
  IJ.run("Duplicate...", "title=" + p.getTitle() + " duplicate range=1-30");
  WindowManager.getImage("VSeg").close()
  return p.getTitle()
示例#15
0
def importMask(evt=None):
  display = Display.getFront()
  # Obtain an image stack
  #imp = IJ.getImage()
  imp = WindowManager.getImage("Labels")

  layerset = display.getLayerSet()
  p = layerset.getProject()

  ali = AreaList(p, "", 0, 0)
  layerset.add(ali)
  p.getProjectTree().insertSegmentations([ali])

  # Obtain the image stack
  stack = imp.getImageStack()
  # Iterate every slice of the stack
  for i in range(1, imp.getNSlices() + 1):
    ip = stack.getProcessor(i) # 1-based
    # Extract all areas (except background) into a map of value vs. java.awt.geom.Area
    m = AreaUtils.extractAreas(ip)
    # Report progress
    if len(m) > 0:
      IJ.log(str(i) + ":" + str(len(m)))
    # Get the Layer instance at the corresponding index
    layer = layerset.getLayers().get(i-1) # 0-based
    # Add the first Area instance to the AreaList at the proper Layer
    if ( m.values().iterator().hasNext() ):
      ali.addArea(layer.getId(), m.values().iterator().next())

  # Change the color of the AreaList
  ali.setColor(Color.red)
  ali.adjustProperties()
  # Ensure bounds are as constrained as possible
  ali.calculateBoundingBox(None)
  # Repaint
  Display.repaint()
示例#16
0
                # Create a snapshot of the images under the area:
                imp = loader.getFlatImage(layer, box, 1, 0xffffffff,
                                          ImagePlus.GRAY8, Patch, False)
                # Set the area as a roi
                imp.setRoi(ShapeRoi(area))
                # Perform measurements (uncalibrated)
                # (To get the calibration, call layerset.getCalibrationCopy())
                stats = ByteStatistics(imp.getProcessor(), moptions,
                                       calibration)
                table.incrementCounter()
                table.addLabel("Name", ali.getTitle())
                table.addValue(0, ali.getId())
                table.addValue(1, index)  # the layer index
                table.addValue(2, layer.getZ())
                table.addValue(3, stats.area)
                table.addValue(4, stats.mean)
        # Update and show the table
        table.show("AreaLists")


# Get the front display, if any:
display = Display.getFront()

if display is not None:
    # Obtain the LayerSet of the current Display canvas:
    layerset = Display.getFront().getLayer().getParent()
    # Measure!
    measureCustom(display.getFront().getLayer().getParent())
else:
    IJ.showMessage("Open a TrakEM2 display first!")
def getDendriticProfiles(ID, biniter):

    tree = Display.getFront().getLayerSet().findById(ID)

    coords = Matrix(getNodeCoordinates(tree))

    # Define axis vectors and origin
    xnorm = Matrix([[1, 0, 0]])
    ynorm = Matrix([[0, 1, 0]])
    znorm = Matrix([[0, 0, 1]])
    center = Matrix([[0, 0, 0]])

    # Project nodes onto axis
    dpx = []
    dpy = []
    dpz = []
    m = coords.getRowDimension()
    for i in range(0, m):
        xstore = Matrix([coords.getRow(i)]) * xnorm.transpose()
        ystore = Matrix([coords.getRow(i)]) * ynorm.transpose()
        zstore = Matrix([coords.getRow(i)]) * znorm.transpose()
        dpx.append(xstore.getRow(0))
        dpy.append(ystore.getRow(0))
        dpz.append(zstore.getRow(0))

    # Count number of nodes which fall in defined interval of pca projection
    xhistovector = []
    yhistovector = []
    zhistovector = []

    # get it back in array form (get rid of list in list of Jarray)

    dpx = [x[0] for x in dpx]
    dpy = [x[0] for x in dpy]
    dpz = [x[0] for x in dpz]

    # Initialize interval size and fix iterations to a specific number
    xbinleft = -34600.0
    ybinleft = -24200.0
    zbinleft = 0
    # --------PARAMETER FOR MACHINE LEARNING-----
    iterations = biniter
    # -------------------------------------------
    xlength = int((35600.0 + 34600.0) / iterations + 0.5)
    ylength = int((21300.0 + 24200.0) / iterations + 0.5)
    zlength = int((22500) / iterations + 0.5)
    xbinright = xbinleft + xlength
    ybinright = ybinleft + ylength
    zbinright = zbinleft + zlength

    # Count elements in bins
    xaxis = []

    # Count lengths in bins
    xdist = []
    ydist = []
    zdist = []

    for i in range(0, iterations):
        counter = 0
        xdiff = 0
        for i in range(0, len(dpx)):
            if dpx[i] <= xbinright and dpx[i] >= xbinleft:
                counter += 1
                xdiff += sqrt(dpy[i] ** 2 + dpz[i] ** 2)  # sqrt(dpy[i]**2) xdist is yvalue
        if counter != 0:
            xdiff /= counter
        xdist.append(xdiff)
        xhistovector.append(counter)
        xaxis.append(xbinleft)
        xbinleft += xlength
        xbinright += xlength

    yaxis = []

    for i in range(0, iterations):
        counter = 0
        ydiff = 0
        for i in range(0, len(dpy)):
            if dpy[i] <= ybinright and dpy[i] >= ybinleft:
                counter += 1
                ydiff += sqrt(dpx[i] ** 2 + dpz[i] ** 2)
        if counter != 0:
            ydiff /= counter
        ydist.append(ydiff)
        yhistovector.append(counter)
        yaxis.append(ybinleft)
        ybinleft += ylength
        ybinright += ylength

    zaxis = []

    for i in range(0, iterations):
        counter = 0
        zdiff = 0
        for i in range(0, len(dpz)):
            if dpz[i] <= zbinright and dpz[i] >= zbinleft:
                counter += 1
                zdiff += sqrt(dpx[i] ** 2 + dpy[i] ** 2)
        if counter != 0:
            zdiff /= counter
        zdist.append(zdiff)
        zhistovector.append(counter)
        zaxis.append(zbinleft)
        zbinleft += zlength
        zbinright += zlength

    # print xdist
    # print ydist
    # print zdist

    """
    #Normalize
  for i in range(0, iterations):
    xhistovector[i]/=float(xlength)
    yhistovector[i]/=float(ylength)
    zhistovector[i]/=float(zlength)
  """
    return xhistovector, yhistovector, zhistovector, xdist, ydist, zdist
示例#18
0
affines = {}
for line in fobj:
    affineline = line.split() 
    affines[affineline[0]] = [affineline[1],affineline[2],affineline[3],affineline[4],affineline[5],affineline[6]]
fobj.close()





# ...
# ...


# Apply the affine to every Patch
from ini.trakem2.display import Display, Patch
from java.awt.geom import AffineTransform

for layer in Display.getFront().getLayerSet().getLayers():
  for patch in layer.getDisplayables(Patch):
    filepath = patch.getImageFilePath()
    print ("filepath\n")
    affine = affines.get(filepath, None) #filepath statt affines eingefuegt
    if affine:
    	for index in range (0,6):
    		affine[index] = float(affine[index])
    		print ("affine[index]", index, affine[index])
    	patch.setAffineTransform(AffineTransform(affine[0], affine[1],affine[2], affine[3], (affine[4]), affine[5]))
    else:
    	print "No affine for filepath:", filepath
    print ("done\n")
# For output a list of tagged nodes in currently active TrakEM2 project
# Change output filename at the bottom

from ini.trakem2.display import AreaList, Display, AreaTree, Connector
import csv

header = ["type", "parentId", "nodeDegree", "layer", "x", "y", "z", "parentName", "shortMeaningfulTitle", "tag"]
foundtags = [header]

areatrees = Display.getFront().getLayerSet().getZDisplayables(AreaTree)
for areatree in areatrees:

    root = areatree.getRoot()
    if root is None:
        continue

    for node in root.getSubtreeNodes():
        tags = node.getTags()
        if tags is None:
            continue
        for tag in tags:
            foundtags.append(
                [
                    "areatrea",
                    areatree.getId(),
                    node.computeDegree(),
                    node.getLayer().getId(),
                    node.getX(),
                    node.getY(),
                    node.getLayer(),
                    areatree.getTitle(),
示例#20
0
def pca(ID, biniter):
  tree = Display.getFront().getLayerSet().findById(ID)

  #Calculate the center of mass
  center = Matrix( [[0,0,0]] )
  coords = Matrix(getNodeCoordinates(tree))
  m=coords.getRowDimension()

  for i in range(0, coords.getRowDimension()):
    center += Matrix([coords.getRow( i )])
  center /= float(m)

  #print center

  """
  x, y, z = 0, 0, 0
  nc = getNodeCoordinates(tree)
  for c in nc:
    x += c[0]
    y += c[1]
    z += c[2]
  print "center:", x/len(nc), y/len(nc), z/len(nc)
  """

  #Define covvariance matrix
  cova = Matrix([[0,0,0],[0,0,0],[0,0,0]])
  diff= Matrix ( [[0,0,0]])
  for i in range(0, m):
    diff = Matrix([coords.getRow( i )]) - center
    cova += diff.transpose() * diff
  cova /= float(m)

  #Evaluedecomposition 
  evaluedecomp = cova.eig()
  evalues = evaluedecomp.getRealEigenvalues()
  evectors = evaluedecomp.getV() # is a Matrix instance

  #Find maximum Eigenvector for maximal Eigenvalue
  maxevaluepos = -1
  maxevalue = 0
  for i in range(0, len(evalues)):
	  if evalues[i] > maxevalue or maxevaluepos==-1:
		  maxevalue=evalues[i]
		  maxevaluepos=i	
  maxevector=evectors.getColumn(maxevaluepos)  #HAVE TO GET VALUES OF COLUMN of evector matrix  i NOT ROW



  #--------------------TEST if Eigenvaluedecomposition is correct-----------
  #vectormatrix=Matrix([evectors.getColumn(maxevaluepos)])
  #test=cova * vectormatrix.transpose()
  #test2=vectormatrix*maxevalue
  #print test
  #print test2
  #-------------------------------------------------------------------------

  #Define a vector over the point cloud and count points in defined interval
  #Normalize vector
  length=sqrt(maxevector[0]**2 + maxevector[1]**2 + maxevector[2]**2)
  normvector = map(lambda x: x / length, maxevector)


  normvectormatrix = Matrix([normvector])
  pca=[]
  m=coords.getRowDimension()
  for i in range(0, m):
    pcastore = (Matrix([coords.getRow( i )]) - center ) * normvectormatrix.transpose()
    pca.append(pcastore.getRow(0))

  #Count number of nodes which fall in defined interval of pca projection -> has to be fixed globally when to compare PCAs!
  counter = 0
  histovector = []
  pca=[ x[0] for x in pca] #get it back in array form (get rid of list in list)
  binleft = -12500 #binleft = min(pca)
  iterations = biniter
  length = int(25000/iterations + 0.5) #int((max(pca)-min(pca))/iterations + 0.5)
  binright = binleft + length

  for i in range(0,iterations):
    for i in range(0, len(pca)):
      if pca[i] <= binright and pca[i] >= binleft:
        counter += 1    
    histovector.append(counter)
    counter=0
    binleft+=length
    binright+=length
  #print "The histogram vector is:", histovector
  return histovector
示例#21
0
# For output a list of tagged nodes in currently active TrakEM2 project
# Change output filename at the bottom

from ini.trakem2.display import AreaList, Display, AreaTree, Connector
import csv

header = [
    'type', 'parentId', 'nodeDegree', 'layer', 'x', 'y', 'z', 'parentName',
    'shortMeaningfulTitle', 'tag'
]
foundtags = [header]

areatrees = Display.getFront().getLayerSet().getZDisplayables(AreaTree)
for areatree in areatrees:

    root = areatree.getRoot()
    if root is None:
        continue

    for node in root.getSubtreeNodes():
        tags = node.getTags()
        if tags is None:
            continue
        for tag in tags:
            foundtags.append([
                'areatrea',
                areatree.getId(),
                node.computeDegree(),
                node.getLayer().getId(),
                node.getX(),
                node.getY(),
示例#22
0
        elem = l[:-1].split(" ")
        fname = elem[0]
        xloc = int(elem[1])
        yloc = int(elem[2])
        zloc = int(elem[3])
        z_list.append(zloc)

        imp = IJ.openImage(os.path.join(img_dir, fname))
        patch = Patch(project, imp.title, xloc, yloc, imp)
        patch.project.loader.addedPatchFrom(os.path.join(img_dir, fname),
                                            patch)

        layer = layerset.getLayer(zloc, 1, True)
        layer.add(patch)

    f.close()

    front = Display.getFront()
    bounds = Rectangle(x=0, y=0, width=20000, height=20000)
    front.resizeCanvas(bounds)

    z_list.sort()
    if z_list[0] != 0:
        layer = layerset.getLayer(0, 1, False)
        layer.remove(False)

    # Save project
    project.saveAs(os.path.join(proj_dir, "montage_v1.xml"), False)
    front.close(project)
示例#23
0
from ini.trakem2.display import Display, Treeline
from java.lang import Math
from jarray import array

def longJumps(t, mindist):
  for nd in t.getRoot().getSubtreeNodes():
    if nd.parent is None:
      continue
    d = Math.sqrt(Math.pow(nd.x - nd.parent.x, 2) + Math.pow(nd.y - nd.parent.y, 2))
    if d > mindist:
      print nd.x, nd.y
      p = array([nd.x, nd.y], 'f')
      aff = t.affineTransform
      aff.transform(p, 0, p, 0, 1)
      cal = t.layerSet.getCalibration()
      print "Off:", p[0] * cal.pixelWidth, p[1] * cal.pixelHeight, (nd.layer.getParent().indexOf(nd.layer) + 1)

for t in Display.getFront().getLayerSet().getZDisplayables(Treeline):
  print t
  longJumps(t, 500)
示例#24
0
def sumDist(id1, biniter):

  distance=profileDistances(id1, biniter)
  xdistance=distance[0]
  ydistance=distance[1]
  zdistance=distance[2]
  
  tree = Display.getFront().getLayerSet().findById(id1)
  coords = Matrix(getNodeCoordinates(tree))
  m=coords.getRowDimension()

  xdist=[]
  ydist=[]
  zdist=[]
  
  #Initialize interval size and fix iterations to a specific coordinate position
  xbinleft = -34600.0
  ybinleft = -24200.0
  zbinleft = 0
  #----------PARAMETER FOR MACHINE LEARNING-----
  iterations =biniter
  #---------------------------------------------
 
  xlength = int((35600.0+34600.0)/iterations + 0.5)
  ylength = int((21300.0+24200.0)/iterations + 0.5)
  zlength = int((22500)/iterations + 0.5)
  
  xbinright = xbinleft + xlength
  ybinright = ybinleft + ylength
  zbinright = zbinleft + zlength  

  sumdist=0.0
  
  for i in range(0, iterations):
    for i in range(0, len(xdistance)):
      if xdistance[i] <= xbinright and xdistance[i] >= xbinleft:
        sumdist += xdistance[i]   
    xdist.append(sumdist)
    sumdist=0.0
    xbinleft += xlength
    xbinright += xlength

  for i in range(0, iterations):
    for i in range(0, len(ydistance)):
      if ydistance[i] <= ybinright and ydistance[i] >= ybinleft:
        sumdist += ydistance[i]     
    ydist.append(sumdist)
    sumdist=0.0
    ybinleft += ylength
    ybinright += ylength

  for i in range(0, iterations):
    for i in range(0, len(zdistance)):
      if zdistance[i] <= zbinright and zdistance[i] >= zbinleft:
        sumdist += zdistance[i]     
    zdist.append(sumdist)
    sumdist=0.0
    zbinleft += zlength
    zbinright += zlength

  sumdistance=[]
  sumdistance= [xdist, ydist, zdist]
  return sumdistance
from mpicbg.trakem2.transform import ExportUnsignedShort

from mpicbg.ij.util import Filter

from net.imglib2.img import ImagePlusAdapter
from net.imglib2.type.numeric.integer import UnsignedShortType
from net.imglib2.type.numeric.real import FloatType

import os

import time



display = Display.getFront()

shape = (3, 3)

subscriptToIndex = [None] * (shape[0]*shape[1])
helperIndex = 0
for x in xrange(shape[0]):
    for y in xrange(shape[1]):
        subscriptToIndex[helperIndex] = (x, y)
        helperIndex += 1


# use coordinate transform folder to specify output folder
ctsFolder     = display.project.getLoader().getCoordinateTransformsFolder().rstrip('/')
lastFolderIdx = len(ctsFolder.split('/')) - 1
itsFolder     = '/'.join(ctsFolder.split('/')[:-1]) + '/trakem2.its/'
    if tags is None:
        return False
    for tag in tags:
        if string in tag.toString():
            return True
    return False

def unsetTagWithString(node, string):
    tags = node.getTags()
    if tags is None:
        return
    for tag in tags:
        if string in tag.toString():
            node.removeTag(tag)

theTag = Tag('EC-link', KeyEvent.VK_C)

connectors = Display.getFront().getLayerSet().getZDisplayables(Connector)
for connector in connectors:
    root = connector.getRoot()
    if root is None:
        continue
    if not containsTag(root, 'EC-link'):
        continue
    # wrong tag position, move to child node
    for childnode in root.getChildrenNodes():
        if not containsTag(childnode, 'EC-link'):
            childnode.addTag(theTag)
            print 'set new tag on', connector.getId()
    unsetTagWithString(root, 'EC-link')
示例#27
0
from mpicbg.trakem2.transform import ExportUnsignedByte
from ini.trakem2 import Project
from ini.trakem2.display import Display
from ij import ImagePlus

project = Project.getProjects()[0]
layers = project.getRootLayerSet().getLayers()
bounds = Display.getFront().getRoi().getBounds()

pair = ExportUnsignedByte.makeFlatImageFromMipMaps(layers[1].getDisplayables(),
                                                   bounds, 0, 1.0)

bp = pair.a
mask = pair.b

ImagePlus("bp", bp).show()
ImagePlus("mask", mask).show()
示例#28
0
    for tag in tags:
        if string in tag.toString():
            return True
    return False


def unsetTagWithString(node, string):
    tags = node.getTags()
    if tags is None:
        return
    for tag in tags:
        if string in tag.toString():
            node.removeTag(tag)


theTag = Tag('EC-link', KeyEvent.VK_C)

connectors = Display.getFront().getLayerSet().getZDisplayables(Connector)
for connector in connectors:
    root = connector.getRoot()
    if root is None:
        continue
    if not containsTag(root, 'EC-link'):
        continue
    # wrong tag position, move to child node
    for childnode in root.getChildrenNodes():
        if not containsTag(childnode, 'EC-link'):
            childnode.addTag(theTag)
            print 'set new tag on', connector.getId()
    unsetTagWithString(root, 'EC-link')
示例#29
0
from java.lang.reflect import Field
from ini.trakem2.persistence import FSLoader
from ini.trakem2.display import Display

loader = Display.getFront().getProject().getLoader()

f = FSLoader.getDeclaredField("cannot_regenerate")
f.setAccessible(True)
f.get(loader).clear()
示例#30
0
  affine = tree.getAffineTransform()
  coords = []
  
  for nd in root.getSubtreeNodes():
    fp = array([nd.getX(), nd.getY()], 'f')
    affine.transform(fp, 0, fp, 0, 1)
    x = fp[0] * calibration.pixelWidth
    y = fp[1] * calibration.pixelHeight
    z = nd.getLayer().getZ() * calibration.pixelWidth   # a TrakEM2 oddity
    # data may be a radius or a java.awt.geom.Area 
    coords.append(Matrix([[x, y, z]]))
  
  return coords

  
tree = Display.getFront().getActive()

m = Matrix( [ [1, 2, 3], [4, 5, 6], [ 7, 8, 10 ] ] )
print "m is:", m
m= m.append( [1,1,1] )
print m
#Calculate the center of mass
center = Matrix([[0,0,0]])
coords = getNodeCoordinates(tree)
for coord in coords:
  center += coord
center /= float(len(coords)) 
print center


#Define covvariance matrix
from ini.trakem2 import Project
from ini.trakem2.display import AreaList, Display, AreaTree, Connector, Coordinate
from ini.trakem2.display.Tree import MeasurePathDistance
from fiji.geom import AreaCalculations
import csv
from jarray import array
from java.awt.geom import Area
from java.awt import Rectangle
import re

project = Project.getProjects().get(0)
projectRoot = project.getRootProjectThing()

display = Display.getFront(project)

neurites = projectRoot.findChildrenOfTypeR("neurite")
notDrawnCo = []
notDrawn = [['layer', 'neurite', 'node']]

for neurite in neurites:
    if re.match(r"^apl", neurite.getTitle()) is None:
        continue
    areatrees = neurite.findChildrenOfTypeR("areatree")
    for areatree in areatrees:
        areatree = areatree.getObject()
        root = areatree.getRoot()
        if root is None:
            continue

        nEmpty = 0
        nNodes = 0
# <graph>
#  <edge id="[the connector id]" origin="[the origin Treeline id]" target="[the target Treeline id]" />
#  ...
# </graph>
# 
# The XML opens in a TextWindow
# 
# While at it, will generate a .sif file for importing the networt into cytoscape
# as well as a list of id vs name.


from ini.trakem2.display import Display, Connector, Treeline
from java.lang import StringBuilder
from ij.text import TextWindow

layerset = Display.getFront().getLayerSet()

xml = StringBuilder("<graph>\n")
sif = StringBuilder()
names = StringBuilder()
indent = ' '
type = Treeline

alltargets = set()

for con in layerset.getZDisplayables(Connector):
	print "Processing Connector", con
	origins = con.getOrigins(type)
	if origins.isEmpty():
		print "Connector without origins:", con
		continue
from __future__ import with_statement
from ini.trakem2.display import Display
from ini.trakem2.utils import Utils
from java.io import File
import os

pps = "/home/albert/Desktop/0111-8/scripts/bzip2-decompress_preprocessor.py"
loader = Display.getFront().getProject().getLoader()

for layer in Display.getFront().getLayerSet().getLayers():
  for patch in layer.getDisplayables():
    loader.setPreprocessorScriptPathSilently(patch, pps)
示例#34
0
# Translate any selected Displayable objects

dx = -90
dy = 129

from ini.trakem2.display import Display

# For any selected objected
for displ in Display.getFront().getSelected():
    displ.getAffineTransform().translate(dx, dy)

Display.repaint()
示例#35
0
from ini.trakem2 import Project
from ini.trakem2.display import AreaList, Display, AreaTree, Connector, Coordinate
from ini.trakem2.display.Tree import MeasurePathDistance
from fiji.geom import AreaCalculations
import csv
from jarray import array
from java.awt.geom import Area
from java.awt import Rectangle
import re

project = Project.getProjects().get(0)
projectRoot = project.getRootProjectThing()

display = Display.getFront(project)

neurites = projectRoot.findChildrenOfTypeR("neurite")
notDrawnCo = []
notDrawn = [['layer', 'neurite', 'node']]

for neurite in neurites:
    if re.match(r"^apl", neurite.getTitle()) is None:
        continue
    areatrees = neurite.findChildrenOfTypeR("areatree")
    for areatree in areatrees:
        areatree = areatree.getObject()
        root = areatree.getRoot()
        if root is None:
            continue

        nEmpty = 0
        nNodes = 0
def timeIt(fn, n_iterations=10):
  elapsed_times = []
  for i in range(n_iterations):
    t0 = System.nanoTime()
    fn()
    t1 = System.nanoTime()
    elapsed_times.append(t1 - t0)

  smallest = min(elapsed_times)
  largest =  max(elapsed_times)
  average =  sum(elapsed_times) / float(n_iterations)
  print "Elapsed time: min", smallest, "max", largest, "average", average
  return elapsed_time

layer = Display.getFront().getLayer()
patch = layer.getDisplayables().get(0)
print patch
pai = patch.createTransformedImage()
print pai
print patch.hasCoordinateTransform()
print patch.getImageProcessor()
first_level_mipmaps_saved = 0

def testCascade():
  global patch, pai, first_level_mipmaps_saved
  print pai
  b = DownsamplerMipMaps.create(
        patch,
        patch.getType(),
		pai.target,
示例#37
0
from ini.trakem2.display import Display, Patch

unique = set()
for patch in Display.getFront().getLayer().getDisplayables(Patch):
  path = patch.getImageFilePath()
  if path in unique:
    patch.remove(False)
  else:
    unique.add(path)

Display.repaint()
示例#38
0
        # Create a snapshot of the images under the area:
        imp = loader.getFlatImage(layer, box, 1, 0xffffffff,
              ImagePlus.GRAY8, Patch, False)
        # Set the area as a roi
        imp.setRoi(ShapeRoi(area))
        # Perform measurements (uncalibrated)
	# (To get the calibration, call layerset.getCalibrationCopy())
        stats = ByteStatistics(imp.getProcessor(), moptions, calibration)
	table.incrementCounter()
	table.addLabel("Name", ali.getTitle())
	table.addValue(0, ali.getId())
	table.addValue(1, index) # the layer index
	table.addValue(2, layer.getZ()) 
	table.addValue(3, stats.area)
	table.addValue(4, stats.mean)
    # Update and show the table
    table.show("AreaLists")


# Get the front display, if any:
display = Display.getFront()

if display is not None:
  # Obtain the LayerSet of the current Display canvas:
  layerset = Display.getFront().getLayer().getParent()
  # Measure!
  measureCustom(display.getFront().getLayer().getParent())
else:
  IJ.showMessage("Open a TrakEM2 display first!")

示例#39
0
def injectNordenTools(display):
    tabs = display.getTabbedPane()
    # Check that it's not there already
    title = "Norden Tools"
    for i in range(tabs.getTabCount()):
        if tabs.getTitleAt(i) == title:
            tabs.remove(i)
            #IJ.showMessage("Norden Tools have already been injected!")
            #return
    # Otherwise, add it new:
    from javax.swing import JPanel, JButton
    panel = JPanel()
    btnExportMask = JButton("Export mask", actionPerformed=nt.exportMask)
    panel.add(btnExportMask)
    btnImportMask = JButton("Import mask", actionPerformed=nt.importMask)
    panel.add(btnImportMask)
    btnOpenStack = JButton("Open Stack", actionPerformed=nt.openStack)
    panel.add(btnOpenStack)
    btnExportSegmentation = JButton("Export segmentation",
                                    actionPerformed=nt.exportSegmentation)
    panel.add(btnExportSegmentation)
    tabs.add(title, panel)
    tabs.setSelectedComponent(panel)


# MAIN
display = Display.getFront()
if display is not None:
    injectNordenTools(display)
else:
    IJ.showMessage("No active TrackEM2-project found. Open one!")
示例#40
0
def sphereCount(ID, biniter):
  #find center of mass
  tree = Display.getFront().getLayerSet().findById(ID)
  coords = Matrix(getNodeCoordinates(tree))
  center = Matrix( [[0,0,0]] )
  m=coords.getRowDimension()


  for i in range(0, m):
    center += Matrix([coords.getRow( i )])
  center /= float(m)

  #calculate all distances of all points to center of mass and put them in a list
  xdist=[]
  ydist=[]
  zdist=[]
  for i in range(0, m):
    xdiff=[]
    if coords.get(i,0) > center.get(0,0):
      xdiff = coords.get(i,0) - center.get(0,0)
    else:
      xdiff = center.get(0,0) - coords.get(i,0)
    xdist.append(xdiff)

  for i in range(0, m):
    ydiff=[]
    if coords.get(i,1) > center.get(0,1):
      ydiff = coords.get(i,1) - center.get(0,1)
    else:
      ydiff = center.get(0,1) - coords.get(i,1)
    ydist.append(ydiff)

  for i in range(0, m):
    zdiff=[]
    if coords.get(i,2) > center.get(0,2):
      zdiff = coords.get(i,2) - center.get(0,2)
    else:
      zdiff = center.get(0,2) - coords.get(i,2)
    zdist.append(zdiff)

  nodeDist=[]
  dist=[]
  for i in range(0, m):
    dist=sqrt(xdist[i]**2 + ydist[i]**2 + zdist[i]**2)
    nodeDist.append(dist)

  iterations=biniter
  Ri=0 #inner radius
  """
  The maximum distance can only be achieved in the xy-plane
  With "fixed" coordinates this will approx. be 35000nm
  To make the scholl-profiles comparable this length has to be used.
  """ 
  scholl=[]
  xaxis=[]
  counter=0
  length= int(35000 / biniter + 0.5)
  Ra=length #outer radius

  for i in range(0, biniter):
    for i in range(0, len(nodeDist)):
      if nodeDist[i] <= Ra and nodeDist[i] >= Ri:  
        counter += 1   
    scholl.append(counter)
    counter=0
    xaxis.append(Ri) # adapt THIS position in all other scripts! Otherwise 1 datapoint is missing!!
    Ri += length
    Ra += length
    
  return scholl, xaxis
from __future__ import with_statement

from ini.trakem2.display import Display

paths = []

for layer in Display.getFront().getLayerSet().getLayers():
  for patch in layer.getDisplayables():
    if patch.isVisible():
      paths.append(patch.getImageFilePath())

print "Number of image paths:", len(paths)

with open("/home/albert/shares/cardona_nearline/Albert/0111-8_whole_L1_CNS/visible_image_filepaths.txt", "w") as f:
  f.write("\n".join(paths))
示例#42
0
  
  for nd in root.getSubtreeNodes():
    fp = array([nd.getX(), nd.getY()], 'f')
    affine.transform(fp, 0, fp, 0, 1)
    x = fp[0] * calibration.pixelWidth
    y = fp[1] * calibration.pixelHeight
    z = nd.getLayer().getZ() * calibration.pixelWidth   # a TrakEM2 oddity
    # data may be a radius or a java.awt.geom.Area 
    coords.append( correct([x, y, z]) )
    #print coords[len(coords)-1]
  return coords

#---------Select tree-----------------  
#tree = Display.getFront().getActive()
ID = 74329
tree = Display.getFront().getLayerSet().findById(ID)
#-------------------------------------


#Calculate the center of mass
center = Matrix( [[0,0,0]] )
coords = Matrix(getNodeCoordinates(tree))
m=coords.getRowDimension()

for i in range(0, coords.getRowDimension()):
  center += Matrix([coords.getRow( i )])
center /= float(m)

print center

"""
from ini.trakem2.display import Display
from mpicbg.trakem2.transform import ExportBestFlatImage
from ij import ImagePlus

patches = Display.getFront().getLayer().getDisplayables()
bounds = Display.getFront().getRoi().getBounds()
backgroundValue = 0
scale = 0.25

e = ExportBestFlatImage(patches, bounds, backgroundValue, scale)
print e.canUseAWTImage()
print e.isSmallerThan2GB()
e.printInfo()

p = e.makeFlatFloatGrayImageAndAlpha()
ImagePlus("grey", p.a).show()
ImagePlus("mask", p.b).show()
def getDendriticProfiles(ID):

  tree = Display.getFront().getLayerSet().findById(ID)

  coords = Matrix(getNodeCoordinates(tree))

  #Define axis vectors and origin
  xnorm = Matrix([[1,0,0]])
  ynorm = Matrix([[0,1,0]])
  znorm = Matrix([[0,0,1]])
  center= Matrix([[0,0,0]])

  #Project nodes onto axis
  dpx=[]
  dpy=[]
  dpz=[]
  m=coords.getRowDimension()
  for i in range(0, m):
    xstore = Matrix([coords.getRow( i )]) * xnorm.transpose()
    ystore = Matrix([coords.getRow( i )]) * ynorm.transpose()
    zstore = Matrix([coords.getRow( i )]) * znorm.transpose()
    dpx.append(xstore.getRow(0))
    dpy.append(ystore.getRow(0))
    dpz.append(zstore.getRow(0))

  #Count number of nodes which fall in defined interval of pca projection
  counter = 0
  xhistovector = []
  yhistovector = []
  zhistovector = []

  #get it back in array form (get rid of list in list of Jarray)

  dpx=[ x[0] for x in dpx]
  dpy=[ x[0] for x in dpy]
  dpz=[ x[0] for x in dpz]

  #Initialize interval size and fix iterations to a specific number
  xbinleft = min(dpx)
  ybinleft = min(dpy)
  zbinleft = min(dpz)
  #-------PARAMETER FOR MACHINE LEARNING--------------
  iterations =100
  #---------------------------------------------------
  
  xlength = int((max(dpx)-min(dpx))/iterations + 0.5)
  ylength = int((max(dpy)-min(dpy))/iterations + 0.5)
  zlength = int((max(dpz)-min(dpz))/iterations + 0.5)
  xbinright = xbinleft + xlength
  ybinright = ybinleft + ylength
  zbinright = zbinleft + zlength

  #Count elements in bins
  xaxis=[]

  for i in range(0,iterations):
    for i in range(0, len(dpx)):
      if dpx[i] <= xbinright and dpx[i] >= xbinleft:
        counter += 1    
    xhistovector.append(counter)
    counter=0
    xbinleft += xlength
    xbinright += xlength
    xaxis.append(xbinleft)
  
  yaxis=[]

  for i in range(0,iterations):
    for i in range(0, len(dpy)):
      if dpy[i] <= ybinright and dpy[i] >= ybinleft:
        counter += 1    
    yhistovector.append(ylength)
    counter=0
    ybinleft += ylength
    ybinright += ylength
    yaxis.append(ybinleft)

  zaxis=[]

  for i in range(0,iterations):
    for i in range(0, len(dpz)):
      if dpz[i] <= zbinright and dpz[i] >= zbinleft:
        counter += 1    
    zhistovector.append(counter)
    counter=0
    zbinleft += zlength
    zbinright += zlength
    zaxis.append(zbinleft)

#Normalize bin-count by division through length
  for i in range(0, iterations):
    xhistovector[i]/=float(xlength)
    yhistovector[i]/=float(ylength)
    zhistovector[i]/=float(zlength)
  
  return xhistovector, yhistovector, zhistovector