Ejemplo n.º 1
0
    def run(self):
        try:
            filepath = self.makeFilePath()
            if os.path.exists(filepath):
                return

            x, y, k = self.coords
            width, height, n_layers = self.dimensions

            # Cube's field of view in XY
            fov = Rectangle(x, y, width, height)

            # Join the bounds of the layers
            r = None
            for b in self.bounds[k:min(k + n_layers, len(bounds))]:
                if r is None:
                    r = Rectangle(b.x, b.y, b.width, b.height)
                else:
                    r.add(b)

            if not fov.intersects(r):
                # Would be empty
                return

            drawImage = Graphics2D.getDeclaredMethod(
                "drawImage", [Image, AffineTransform, ImageObserver])
            drawImage.setAccessible(True)
            dispose = Graphics.getDeclaredMethod("dispose", [])
            dispose.setAccessible(True)

            # Populate and write cube
            stack = ImageStack(width, height)
            for layer in self.layers[k:min(k + n_layers, len(self.layers))]:
                img = layer.getProject().getLoader().getFlatAWTImage(
                    layer, fov, 1.0, -1, ImagePlus.GRAY8, Patch, None, False,
                    Color.black)
                bi = BufferedImage(img.getWidth(None), img.getHeight(None),
                                   BufferedImage.TYPE_BYTE_GRAY)
                g = bi.createGraphics()
                aff = AffineTransform(1, 0, 0, 1, 0, 0)
                #g.drawImage(img, aff, None) # Necessary to bypass issues that result in only using 7-bits and with the ByteProcessor constructor
                drawImage.invoke(g, [img, aff, None])
                #g.dispose()
                dispose.invoke(g, [])
                g = None
                img = None
                stack.addSlice("", ByteProcessor(bi))
                bi.flush()
                bi = None

            imp = ImagePlus("x=%s y=%s k=%s" % (x, y, k), stack)
            Utils.ensure(filepath)
            FileSaver(imp).saveAsZip(filepath)
            imp.flush()
            imp = None
        except:
            e = sys.exc_info()
            System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" +
                               str(e[2]))
            System.out.println(traceback.format_exception(e[0], e[1], e[2]))
Ejemplo n.º 2
0
def showImgWithFullWindow(width=None, height=None):
    """ This function shows the image from current IDV window while in GUI mode. optional arguments are width and height in pixels, they
    currently default to 600 and 400"""
    from java.util import Base64  ##only in java8
    from javax.imageio import ImageIO
    from java.io import ByteArrayOutputStream
    from ucar.unidata.ui.ImageUtils import resize, toBufferedImage
    import java
    import java.awt.Robot as Robot
    import java.awt.Rectangle as Rectangle
    import java.awt.Toolkit as Toolkit
    from ucar.unidata.util import Misc
    VM = idv.getViewManager()
    myframe = VM.getDisplayWindow().getComponent()
    robotx = Robot(myframe.getGraphicsConfiguration().getDevice())
    VM.toFront()
    #robotx.delay(250)
    Misc.sleep(350)
    pause()
    img = robotx.createScreenCapture(
        Rectangle(myframe.getX(), myframe.getY(), myframe.getWidth(),
                  myframe.getHeight()))
    if width != None and height != None:
        img = toBufferedImage(resize(img, width, height))
    bos = ByteArrayOutputStream()
    ImageIO.write(img, "png",
                  Base64.getEncoder().wrap(bos))
    data = bos.toString("UTF-8")
    return {"display": "image", "data": data}
Ejemplo n.º 3
0
def showImgWithLegend(width=None, height=None):
    """ This function shows the image and legend from current IDV window while in GUI mode. Optional arguments are width and height in pixels, they currently default to 600 and 400"""
    from java.util import Base64  ##only in java8
    from javax.imageio import ImageIO
    from java.io import ByteArrayOutputStream
    from ucar.unidata.ui.ImageUtils import resize, toBufferedImage
    import java
    import java.awt.Robot as Robot
    import java.awt.Rectangle as Rectangle
    import java.awt.Toolkit as Toolkit
    from ucar.unidata.util import Misc
    VM = idv.getViewManager()
    VMC = VM.getContents()
    VMCC = VMC.getComponent(
        1
    )  # the view and legend ; 0 is left most part of view window with controls for perspective views
    siz = VMCC.getSize()
    loc = VMCC.getLocationOnScreen()
    gc = VMCC.getGraphicsConfiguration()
    loc.x -= gc.getBounds().x
    loc.y -= gc.getBounds().y
    robotx = Robot(gc.getDevice())
    VM.toFront()
    Misc.sleep(250)
    img = robotx.createScreenCapture(
        Rectangle(loc.x, loc.y, siz.width, siz.height))
    if width != None and height != None:
        img = toBufferedImage(resize(img, width, height))
    bos = ByteArrayOutputStream()
    ImageIO.write(img, "png",
                  Base64.getEncoder().wrap(bos))
    data = bos.toString("UTF-8")
    return {"display": "image", "data": data}
Ejemplo n.º 4
0
    def isEmpty(self):
        # Check if the cube would have any data
        x, y, k = self.coords
        width, height, n_layers = self.dimensions
        # Cube's field of view in XY
        fov = Rectangle(x, y, width, height)

        # Join the bounds of the layers
        r = None
        for b in self.bounds[k:min(k + n_layers, len(bounds))]:
            if r is None and b is not None:  # can be none when the Layer is empty
                r = Rectangle(b.x, b.y, b.width, b.height)
            elif b is not None:
                r.add(b)

        # Return True if not intersecting
        return r is None or not fov.intersects(r)
Ejemplo n.º 5
0
def run(title):
    gd = ij.gui.GenericDialog('Record Desktop')
    gd.addNumericField('Max. frames:', 50, 0)
    gd.addNumericField('Milisecond interval:', 300, 0)
    gd.addSlider('Start in (seconds):', 0, 20, 5)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    delay = int(gd.getNextNumber())

    snaps = []

    try:
        while delay > 0:
            ij.IJ.showStatus('Starting in ' + str(delay) + 's.')
            time.sleep(1)  # one second
            delay -= 1
        ij.IJ.showStatus('')
        ij.IJ.showStatus("Starting...")
        out.println("Starting...")
        # start capturing
        robot = Robot()
        box = Rectangle(ij.IJ.getScreenSize())
        start = currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        # Initial shot
        snaps.append(robot.createScreenCapture(box))
        while len(snaps) < n_frames and last - start < n_frames * interval:
            now = currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                snaps.append(robot.createScreenCapture(box))
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)  # time in seconds
        # Create stack
        out.println("End")
        awt = snaps[0]
        stack = ij.ImageStack(awt.getWidth(None), awt.getHeight(None), None)
        t = 0
        for snap, real_interval in zip(snaps, intervals):
            stack.addSlice(str(ij.IJ.d2s(t, 3)),
                           ij.ImagePlus('', snap).getProcessor())
            snap.flush()
            t += real_interval

        ImagePlus("Desktop recording", stack).show()
    except Exception, e:
        print "Some error ocurred:"
        print e
        for snap in snaps:
            snap.flush()
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
Ejemplo n.º 7
0
def generate_image(width, height):
    renderer = StaticRenderer()
    renderer.setTree(GVTBuilder().build(context, document))
    transform = AffineTransform()
    transform.translate(-svg_x, -svg_y)
    transform.scale(width / svg_width, height / svg_height)
    renderer.setTransform(transform)
    renderer.updateOffScreen(width, height)
    renderer.repaint(Rectangle(0, 0, width, height))
    return renderer.getOffScreen()
Ejemplo n.º 8
0
def fixAreatreeArea(areatree):
    # Append a 1-pixel square area for nodes without any area
    # this will fix using findZDisplayables for finding areatree, 
    #     including connector.getTargets(), connector.getOrigins() etc.
    if not isinstance(areatree, AreaTree):
        print "Error: input must be an AreaTree"
        return
    root = areatree.getRoot()
    if root is None:
        return
    for nd in root.getSubtreeNodes():
        a = nd.getArea()
        a.add(Area(Rectangle(int(nd.getX()), int(nd.getY()), 1, 1)))
        nd.setData(a)
Ejemplo n.º 9
0
 def roiModified(self, imp, ID):
     """ When the ROI of the active image changes, update the textfield values. """
     if imp != IJ.getImage():
         return  # ignore if it's not the active image
     roi = imp.getRoi()
     if not roi or Roi.RECTANGLE != roi.getType():
         return  # none, or not a rectangle ROI
     bounds = roi.getBounds()
     if 0 == roi.getBounds().width + roi.getBounds().height:
         bounds = Rectangle(0, 0, imp.getWidth(), imp.getHeight())
     self.textfields[0].setText(str(bounds.x))
     self.textfields[1].setText(str(bounds.y))
     self.textfields[2].setText(str(bounds.width))
     self.textfields[3].setText(str(bounds.height))
Ejemplo n.º 10
0
 def checkColor(self, SCREEN):
     print" checkColor !!"
     i = Robot().createScreenCapture(Rectangle(SCREEN.getX(),
                 SCREEN.getY(), self.patternW, self.patternH))
     bColor = Color(200, 4, 4)
     pColor = Color(45, 48, 177)
     print"self.patternW:"+self.patternW+ " self.patternH:"+self.patternH
     for x in range(0, self.patternW):
         for y in range(0, self.patternH):
             print" color"
             print i.getRGB(x, y)
             if bColor == Color(i.getRGB(x, y)):
                 return "B"
             if pColor == Color(i.getRGB(x, y)):
                 return "P"
Ejemplo n.º 11
0
    def transformRefView(self, ref):
        """ Transforms ref src_rect from physical units to pixels 
		
		Parameters
		----------
		ref : list
			Rectangle (x, y, width, height) to display. x and y are coordinates of
			upper-left corner of the Rectangle. ref is in physical units.
			
		"""
        x = int(self.calibration.getRawX(ref[0]))
        y = int(self.calibration.getRawY(ref[1]))
        width = int(self.calibration.getRawX(ref[2]))
        height = int(self.calibration.getRawY(ref[3]))

        return Rectangle(x, y, width, height)
Ejemplo n.º 12
0
    def save_screenshot_to(self, path):
        """Saves a screenshot to the specified file.

        The directory holding the file must exist or an exception is raised.
        """
        path = os.path.abspath(path.replace('/', os.sep))
        if not os.path.exists(os.path.dirname(path)):
            raise RuntimeError(
                "Directory '%s' where to save the screenshot does "
                "not exist" % os.path.dirname(path))
        screensize = Toolkit.getDefaultToolkit().getScreenSize()
        rectangle = Rectangle(0, 0, screensize.width, screensize.height)
        image = Robot().createScreenCapture(rectangle)
        ImageIO.write(image, "jpg", File(path))
        print "Screenshot saved to '%s'" % path
        return path
Ejemplo n.º 13
0
def exportFlatRoi(project, scaleFactor, x, y, w, h, layer, saveName):
	loader = project.getLoader()
	rectangle = Rectangle(x-int(w/2),y-int(h/2),w,h)
	patches = layer.find(Patch, x, y)
	print patches
	# IJ.log('patches' + str(patches))

	for p, patch in enumerate(patches):
		visible = patch.visible
		patch.visible = True
		tiles = ArrayList()
		tiles.add(patch)
		print 'tiles',tiles
		print 'rectangle',rectangle
		IJ.log('Patch ' + str(patch) + ' cropped with rectangle ' + str(rectangle) )
		imp = loader.getFlatImage(layer, rectangle, scaleFactor, 0x7fffffff, ImagePlus.GRAY8, Patch, tiles, True, Color.black, None)
		exportName = saveName + '_' + str(int(p)) + '.tif'
		IJ.save(imp, exportName)
		patch.visible = visible
Ejemplo n.º 14
0
def rigidAlignment(projectPath, params, name = '', boxFactor = 1):
	# rigid alignment outside trakem2 with register virtual stack plugin because bug in trakem2
	projectFolder = os.path.dirname(projectPath)
	projectName = os.path.splitext(os.path.basename(projectPath))[0]
	project, loader, layerset, nLayers = openTrakemProject(projectPath)

	exportForRigidAlignmentFolder = mkdir_p(os.path.join(projectFolder, 'exportForRigidAlignment'))
	resultRigidAlignmentFolder = mkdir_p(os.path.join(projectFolder, 'resultRigidAlignment'))
	
	bb = layerset.get2DBounds()	
	roi = Rectangle(int(bb.width/2 * (1 - boxFactor)), int(bb.height/2 * (1 - boxFactor)), int(bb.width*boxFactor), int(bb.height*boxFactor))	
	boxPath = os.path.join(resultRigidAlignmentFolder, 'alignmentBox.txt')
	writeRectangle(roi, boxPath)

	exportFlat(project, exportForRigidAlignmentFolder, 1, baseName = 'exportForRigidAlignment', roi = roi)

	referenceName = naturalSort(os.listdir(exportForRigidAlignmentFolder))[0]
	use_shrinking_constraint = 0
	IJ.log('Rigid alignment with register virtual stack')
	Register_Virtual_Stack_MT.exec(exportForRigidAlignmentFolder, resultRigidAlignmentFolder, resultRigidAlignmentFolder, referenceName, params, use_shrinking_constraint)
	time.sleep(2)
	IJ.log('Warning: rigidAlignment closing all existing windows')
	WindowManager.closeAllWindows() # problematic because it also closes the log window
	
	# IJ.getImage().close()

	for l, layer in enumerate(layerset.getLayers()):
		imagePath = os.path.join(exportForRigidAlignmentFolder, 'exportForRigidAlignment_' + str(l).zfill(4) + '.tif')
		transformPath = os.path.join(resultRigidAlignmentFolder, 'exportForRigidAlignment_' + str(l).zfill(4) + '.xml')
		aff = getAffFromRVSTransformPath(transformPath)

		for patch in layer.getDisplayables(Patch):
			patch.setLocation(patch.getX()-roi.x, patch.getY()-roi.y) # compensate for the extracted bounding box
			# patch.setLocation(roi.x, roi.y) # compensate for the extracted bounding box
			currentAff = patch.getAffineTransform()
			currentAff.preConcatenate(aff)
			patch.setAffineTransform(currentAff)

	resizeDisplay(layerset)
	project.save()
	closeProject(project)
	IJ.log('All LM layers have been aligned in: ' + projectPath)
Ejemplo n.º 15
0
    def __init__(self):
        dataDir = Settings.dataDir + 'WorkingWithBarcodeRecognition/AdvancedBarcodeRecognitionFeatures/ReadBarcodeFromSpecificRegion/'

        # Open the stream. Read only access is enough for Aspose.BarCode to load an image.
        stream = FileInputStream(dataDir + "test.png")

        # Create an instance of BarCodeReader class
        # and specify an area to look for the barcode

        barcode_reader_type = BarCodeReadType
        reader = BarCodeReader(stream, Rectangle(0, 0, 10, 50),
                               barcode_reader_type.Code39Standard)

        # TRead all barcodes in the provided area
        while (reader.read()):
            # Display the codetext and symbology type of the barcode found
            print "Codetext: "
            print reader.getCodeText()
            print " Symbology: "
            print reader.getReadType()

        # Close reader
        reader.close()
Ejemplo n.º 16
0
            affineCroppedFolder = os.path.join(LMFolder,
                                               'affineCropped_' + channel)

            LMMosaicsPath = fc.cleanLinuxPath(
                os.path.join(
                    LMFolder, 'exported_downscaled_1_' + channel,
                    'exported_downscaled_1_' + channel + '_' +
                    str(l).zfill(4) + '.tif'))

            patch = Patch.createPatch(pZ, LMMosaicsPath)
            layerZ.add(patch)
            IJ.log('Setting the affineTransform ' + str(affTransform))
            patch.setAffineTransform(affTransform)
            patch.updateBucket()

            bb = Rectangle(0, 0, widthEM, heightEM)
            affineCroppedIm = loaderZ.getFlatImage(layerZ, bb, 1, 0x7fffffff,
                                                   ImagePlus.GRAY8, Patch,
                                                   layerZ.getAll(Patch), True,
                                                   Color.black, None)
            affineCroppedImPath = os.path.join(
                affineCroppedFolder,
                'affineCropped_' + channel + '_' + str(l).zfill(4) + '.tif')
            IJ.save(affineCroppedIm, affineCroppedImPath)
            affineCroppedIm.close()

            layerZ.remove(patch)
            layerZ.recreateBuckets()
            IJ.log('Has been written: ' + str(affineCroppedImPath))
fc.closeProject(pZ)  # close dummy trakem
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
 def _java_screenshot(self, path):
     size = Toolkit.getDefaultToolkit().getScreenSize()
     rectangle = Rectangle(0, 0, size.width, size.height)
     image = Robot().createScreenCapture(rectangle)
     ImageIO.write(image, 'jpg', File(path))
Ejemplo n.º 19
0
        layerset = areatree.getLayerSet()
        calibration = layerset.getCalibration()
        affine = areatree.getAffineTransform()
        # outAndInArray = areatree.findConnectors()
        for nd in root.getSubtreeNodes():
            # get node coordinates, from tut on web
            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

            # get node connections, in/out synapse number, synapse id
            # NOTE: this method seems to be affected by display zoom value
            area = Area(Rectangle(int(fp[0]), int(fp[1]), 1, 1))
            # area.transform(affine)
            inAndOuts = layerset.findZDisplayables(Connector, nd.getLayer(),
                                                   area, False, False)
            outgoing = []
            incoming = []
            for connector in inAndOuts:
                if connector is None:
                    break
                if connector.intersectsOrigin(area, nd.getLayer()):
                    outgoing.append(connector)
                else:
                    incoming.append(connector)
            nInputs = len(incoming)
            nOutputs = len(outgoing)
            outgoingIds = [oc.getId() for oc in outgoing]
Ejemplo n.º 20
0
from java.util.concurrent import Executors
from java.lang import Runtime
from java.awt import Rectangle
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from ij import IJ

# Open Nile Bend sample image
imp = IJ.getImage()
#imp = IJ.openImage("https://imagej.nih.gov/ij/images/NileBend.jpg")
img = IL.wrapRGBA(imp)

# Extract red channel: alpha:0, red:1, green:2, blue:3
red = Converters.argbChannel(img, 1)

# Cut out two overlapping ROIs
r1 = Rectangle(1708, 680, 1792, 1760)
r2 = Rectangle(520, 248, 1660, 1652)
cut1 = Views.zeroMin(
    Views.interval(red, [r1.x, r1.y],
                   [r1.x + r1.width - 1, r1.y + r1.height - 1]))
cut2 = Views.zeroMin(
    Views.interval(red, [r2.x, r2.y],
                   [r2.x + r2.width - 1, r2.y + r2.height - 1]))

# Thread pool
exe = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())

try:
    # PCM: phase correlation matrix
    pcm = PhaseCorrelation2.calculatePCM(cut1, cut2,
                                         ArrayImgFactory(FloatType()),
Ejemplo n.º 21
0
 def getDefaultFrameBounds(self):
     return Rectangle(50, 50, 300, 600)
Ejemplo n.º 22
0
    def run(self):
        global filepath
        gl.log("running MagicDrawAnimator2")
        mode = 0
        if mode == 0:
            #filepath = "c:\\Users\\bclement\\git\\bae\\simulationSnapshot.Scenario_medium_2012.txt"
            #filepath = "c:\\Users\\bclement\\Desktop\\large6.txt"
            #filepath = "c:\\Users\\bclement\\Desktop\\foo12.txt"
            #filepath = "/Users/mjackson/Desktop/testSim.txt"
            gl.log("default filepath = %s" % filepath)
            filepath = JOptionPane.showInputDialog(None,
                                                   "Select File to Animate",
                                                   "Select File",
                                                   JOptionPane.PLAIN_MESSAGE,
                                                   None, None, filepath)
            gl.log("reading events from " + filepath)
            self.events = []
            try:
                f = open(filepath, "r")
            except:
                gl.log("can't find file @ %s" % filepath)
                return
            lastTime = float(0.0)
            latestTime = float(-1.0e20)
            earliestTime = float(1.0e20)
            gl.log(
                "MagicDrawAnimator2: before simulation, loading events from " +
                str(filepath))
            print(
                "MagicDrawAnimator2: before simulation, loading events from " +
                str(filepath))
            for line in f.readlines():
                gl.log("read line = " + line)
                x = re.search(
                    "(\d*)[^0-9: \t\n\r\f\v]*\s*:\s*\S*\s*(\S*) -> (\S*)\s*(\S*) ==>",
                    line)
                y = re.search("(\S*) -> (\S*)\s*(\S*) ==>", line)
                if x:
                    eventTime = float(x.groups()[0])
                    lastTime = eventTime
                    action = x.groups()[2]
                    cid = x.groups()[3]
                    ctype = x.groups()[1]
                    #gl.log("%s %s (%s)" % (action.upper(), cid, ctype))
                elif y:
                    eventTime = lastTime
                    action = y.groups()[1]
                    cid = y.groups()[2]
                    ctype = y.groups()[0]
                    #gl.log("%s %s (%s)" % (action.upper(), cid, ctype))
                elif line.startswith("---"):
                    gl.log(line)
                    continue
                else:
                    continue
                #gl.log("%s %s (%s)" % (action.upper(), cid, ctype))
                if any([x in cid for x in ["Main"]]):
                    #gl.log("    ---> Skipping - can't animate Main")
                    continue
                if re.search("(_)?Activity(_.*)?(?!\S)", ctype):
                    #gl.log("    ---> Skipping - can't animate the Activity object!")
                    continue
                try:
                    if eventTime < earliestTime:
                        earliestTime = eventTime
                    if eventTime > latestTime:
                        latestTime = eventTime
                    evt = event(eventTime, action, cid, ctype)
                    try:
                        self.events.append(evt)
                    except:
                        gl.log("NESTED ARGHHHHH")
                except:
                    gl.log("ARRGHHH")

            print("MagicDrawAnimator2: finished loading events from " +
                  str(filepath))
            gl.log("MagicDrawAnimator2: finished loading events from " +
                   str(filepath))

            elementsNotEnded = []
            try:
                mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2()
                #self.playEvents(mda)
                if self.timeScale == 0.0:
                    gl.log("*** ZERO TIMESCALE: setting timeScale to 1.0")
                    self.timeScale = 1.0
                if usingDialogs:
                    JOptionPane.showMessageDialog(
                        self.frame, "Click ok to start simulation.")
                #simulatedDuration = (float(latestTime) - float(earliestTime))/ float(self.timeScale)
                simulatedDuration = (latestTime -
                                     earliestTime) / self.timeScale
                lastTime = earliestTime
                elapsedTime = earliestTime
                simStartTime = earliestTime / self.timeScale  #start at time of first event
                elapsedSimTime = simStartTime  #start at time of first event
                zeroTime = time.time()
            except:
                exceptionType, exceptionValue, exceptionTraceback = sys.exc_info(
                )
                gl.log("*** EXCEPTION:")
                messages = traceback.format_exception(exceptionType,
                                                      exceptionValue,
                                                      exceptionTraceback)
                for message in messages:
                    gl.log(message)
            print("MagicDrawAnimator2: starting simulation with timeScale = " \
                   + str(self.timeScale) + "; last event at " + str(latestTime) \
                   + " scaling to " + str(simulatedDuration) + " seconds")
            gl.log("MagicDrawAnimator2: starting simulation with timeScale = " \
                   + str(self.timeScale) + "; last event at " + str(latestTime) \
                   + " scaling to " + str(simulatedDuration) + " seconds")
            try:
                for evt in self.events:
                    #gl.log("EVENT at " + str(evt.eventTime))
                    #Sprint("EVENT at " + str(evt.eventTime))
                    try:
                        timeOfNextEvent = (float(evt.eventTime) +
                                           0.0) / self.timeScale
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info(
                        )
                        gl.log("*** EXCEPTION:")
                        messages = traceback.format_exception(
                            exceptionType, exceptionValue, exceptionTraceback)
                        for message in messages:
                            gl.log(message)
                    #print("1")
                    if evt.eventTime != lastTime:
                        mda.doThePaint(
                        )  #paint all events occurring at the previous event time
                        lastTime = float(evt.eventTime)
                    #print("2")
                    if timeOfNextEvent > elapsedSimTime:
                        print("sleeping sim time of next event(" + str(timeOfNextEvent) \
                               + ") - elapsed sim time(" + str(elapsedSimTime) + ") = " \
                               + str(timeOfNextEvent - elapsedSimTime) + " seconds")
                        gl.log("sleeping sim time of next event(" + str(timeOfNextEvent) \
                               + ") - elapsed sim time(" + str(elapsedSimTime) + ") = " \
                               + str(timeOfNextEvent - elapsedSimTime) + " seconds")
                        if (timeOfNextEvent - elapsedSimTime) > 300:
                            gl.log("found time jump > 300")
                            break
                        time.sleep(timeOfNextEvent - elapsedSimTime)

                    if "TimeVaryingMap" in evt.componentId:
                        try:
                            val = evt.action.split("=")[1]
                        except:
                            val = evt.action
                        gl.log("    ---> (%s) SETTING VALUE of %s: %s" %
                               (evt.eventTime, evt.componentType, val))

                    elif evt.componentType.startswith(
                            "sig") and "ObjectFlow" in evt.componentId:
                        sid = evt.componentType.strip("sig")
                        if "null" in evt.action and sid in elementsNotEnded:
                            gl.log("    ---> (%s) ENDING SIGNAL %s" %
                                   (evt.eventTime, sid))
                            mda.end(sid)
                            elementsNotEnded.remove(sid)
                        elif "null" not in evt.action:
                            gl.log("    ---> (%s) STARTING SIGNAL %s ==> %s" %
                                   (evt.eventTime, sid, evt.action))
                            txt = ""
                            try:
                                txt = evt.action.split("=")[1]
                            except:
                                txt = evt.action
                            mda.start(sid, txt)
                            if sid not in elementsNotEnded:
                                elementsNotEnded.append(sid)

                    elif "start" in evt.action:
                        gl.log("    ---> (%s) STARTING" % evt.eventTime)
                        mda.start(evt.componentId)
                        if evt.componentId not in elementsNotEnded:
                            elementsNotEnded.append(evt.componentId)
                    elif "end" in evt.action:
                        gl.log("    ---> (%s) ENDING" % evt.eventTime)
                        mda.end(evt.componentId)
                        if evt.componentId in elementsNotEnded:
                            elementsNotEnded.remove(evt.componentId)
                    t = time.time()
                    elapsedSimTime = t - zeroTime + simStartTime
                    elapsedTime = self.timeScale * elapsedSimTime
                    gl.log("Debug: elapsed time = " + str(elapsedSimTime))
            except:
                self.handleException()
            if len(elementsNotEnded) > 0:
                gl.log("Ending Still-Active Events:")
                for e in elementsNotEnded:
                    gl.log("    ending %s " % e)
                    try:
                        mda.end(e)
                    except:
                        self.handleException()
                mda.doThePaint()

            else:
                gl.log("All Events Completed")

            gl.log("DONE")

        elif mode == 1:
            e = "_17_0_2_edc0357_1352328158277_34448_20209"
            mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2()
            gl.log("Starting e (%s)" % e)
            mda.start(e, "Porpoise Hork")
            mda.doThePaint()

            i = 3
            while i > 0:
                i -= 1
                gl.log(".")
                time.sleep(1)

            gl.log("ending e")
            mda.end(e)
            mda.doThePaint()

        elif mode == 2:
            try:
                mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2()
                e = "_17_0_2_edc0357_1352328158277_34448_20209"  # in the usePower activity
                gl.log("Starting e (%s)" % e)
                mda.start(e)
                mda.doThePaint()
                tb = None
                pem = PresentationElementsManager.getInstance()
                sm = SessionManager.getInstance()
                try:
                    sym = mda.gimmeTheSymbol(e)
                    midPoint = sym.getMiddlePoint()
                    sm.createSession("make box!")
                    try:
                        parentPM = sym.getPropertyManager()
                        c = Color.GREEN
                        tb = pem.createTextBox(sym, midPoint)
                        newBounds = Rectangle(15, 15)
                        newBounds.setLocation(midPoint)
                        pem.reshapeShapeElement(tb, newBounds)
                        pem.setText(tb, "     gobblelkajdlfkjakj")
                        pem.setPresentationElementProperties(tb, parentPM)
                        sm.closeSession()
                    except:
                        sm.cancelSession()
                        self.handleException()
                except:
                    self.handleException()

                i = 3
                while i > 0:
                    i -= 1
                    gl.log(".")
                    time.sleep(1)

                gl.log("ending e")
                mda.end(e)
                if tb:
                    sm.createSession("deleteBox!")
                    try:
                        pem.deletePresentationElement(tb)
                        sm.closeSession()
                    except:
                        sm.cancelSession()
                        self.handleException()
                mda.doThePaint()
            except:
                self.handleException()
Ejemplo n.º 23
0
def readRectangle(path):
	with open(path,'r') as f:
		res = []
		for i, line in enumerate(f):
			res.append(int(line))
	return Rectangle(res[0],res[1],res[2],res[3])
Ejemplo n.º 24
0
def measure(stack, cells, nuclei):
    time = [ (t-1)*cal.frameInterval for t in range(T+1) ]
    cellValues0 = [ 0.0 for t in range(T+1) ]
    cellValues1 = [ 0.0 for t in range(T+1) ]
    cellAreas0 = [ 0.0 for t in range(T+1) ]
    cellAreas1 = [ 0.0 for t in range(T+1) ]
    nucleusValues0 = [ 0.0 for t in range(T+1) ]
    nucleusValues1 = [ 0.0 for t in range(T+1) ]
    nucleusAreas0 = [ 0.0 for t in range(T+1) ]
    nucleusAreas1 = [ 0.0 for t in range(T+1) ]
    nonNucleusValues0 = [ 0.0 for t in range(T+1) ]
    nonNucleusValues1 = [ 0.0 for t in range(T+1) ]

    for t in range(1,T+1):
        ip = stack.getProcessor(t)

        if cells[t] is None:
            continue


        #subtract background Z from all intensity Z measurements
        if cells [t] is None:
            print("Nocellsfound" + str(t))
        bothCells = ShapeRoi(cells[t][0]).or(ShapeRoi(cells[t][1]))
        backRoi = ShapeRoi(Rectangle(0,0,imp.getWidth(),imp.getHeight())).not( bothCells )


        ip.setRoi(backRoi)
        backMean = ip.getStatistics().mean

        ip.setRoi( cells[t][0] )
        stats0 = ip.getStatistics()
        cellValues0[t] = stats0.mean - backMean
        cellAreas0[t] = stats0.area * cal.pixelWidth * cal.pixelHeight
        nuc0 = None
        for nuc in nuclei[t]:
            rect = nuc.getBounds()
            nx = int(rect.x+(rect.width/2.0))
            ny = int(rect.y+(rect.height/2.0))
            if cells[t][0].contains(nx,ny):
                nuc0 = nuc
                break
        if nuc0 is not None:
            ip.setRoi( nuc0 )
            nucStats0 = ip.getStatistics()
            nucleusValues0[t] = nucStats0.mean - backMean
            nucleusAreas0[t] = nucStats0.area * cal.pixelWidth * cal.pixelHeight
            nuc0.setPosition(0,0,t)
            nuc0.setStrokeColor(Color.CYAN)
            ol.add(nuc0)
            nonnucRoi0 = ShapeRoi(cells[t][0]).not( ShapeRoi(nuc0) )
            ip.setRoi( nonnucRoi0 )
            nonNucleusValues0[t] = ip.getStatistics().mean - backMean

        ip.setRoi( cells[t][1] )
        stats1 = ip.getStatistics()
        cellValues1[t] = stats1.mean - backMean
        cellAreas1[t] = stats1.area * cal.pixelWidth * cal.pixelHeight
        nuc1 = None
        for nuc in nuclei[t]:
            rect = nuc.getBounds()
            nx = int(rect.x+(rect.width/2.0))
            ny = int(rect.y+(rect.height/2.0))
            if cells[t][1].contains(nx,ny):
                nuc1 = nuc
                break
        if nuc1 is not None:
            ip.setRoi( nuc1 )
            nucStats1 = ip.getStatistics()
            nucleusValues1[t] = nucStats1.mean - backMean
            nucleusAreas1[t] = nucStats1.area * cal.pixelWidth * cal.pixelHeight
            nuc1.setPosition(0,0,t)
            nuc1.setStrokeColor(Color.CYAN)
            ol.add(nuc1)
            nonnucRoi1 = ShapeRoi(cells[t][1]).not( ShapeRoi(nuc1) )
            ip.setRoi( nonnucRoi1 )
            nonNucleusValues1[t] = ip.getStatistics().mean - backMean

    rt = ResultsTable()
    rt.showRowNumbers(False)
    for t in range(1,T+1):
        rt.setValue("Time ("+cal.getTimeUnit()+")", t-1, IJ.d2s(time[t],1))
        areaRatio = cellAreas0[t] / cellAreas1[t] if cellAreas0[t]>0 and cellAreas1[t]>0 else 0.0
        rt.setValue("Cell 0:Cell 1 Area Ratio", t-1, areaRatio)

        nucleusRatio = nucleusValues0[t] / nucleusValues1[t] if nucleusValues0[t]>0 and nucleusValues1[t]>0 else 0.0
        rt.setValue("Cell 0:Cell 1 Nucleus Ratio", t-1, nucleusRatio)
        nonNucleusRatio = nonNucleusValues0[t] / nonNucleusValues1[t] if nonNucleusValues0[t]>0 and nonNucleusValues1[t]>0 else 0.0
        rt.setValue("Cell 0:Cell 1 Non-Nucleus Ratio", t-1, nonNucleusRatio)

        nnnRatio0 = nucleusValues0[t] / nonNucleusValues0[t] if nucleusValues0[t]>0 and nonNucleusValues0[t]>0 else 0.0
        rt.setValue("Cell 0 Nucleus:Non-Nucleus Ratio", t-1, nnnRatio0)
        nnnRatio1 = nucleusValues1[t] / nonNucleusValues1[t] if nucleusValues1[t]>0 and nonNucleusValues1[t]>0 else 0.0
        rt.setValue("Cell 1 Nucleus:Non-Nucleus Ratio", t-1, nnnRatio1)

        rt.setValue("Cell 0 (red) Area ("+cal.getUnit()+u"\u00b2"+")", t-1, cellAreas0[t])
        rt.setValue("Cell 0 Nucleus Area ("+cal.getUnit()+u"\u00b2"+")", t-1, nucleusAreas0[t])
        rt.setValue("Cell 0 All", t-1, cellValues0[t])
        rt.setValue("Cell 0 Nucleus", t-1, nucleusValues0[t])
        rt.setValue("Cell 0 Non-Nucleus", t-1, nonNucleusValues0[t])
        rt.setValue("Cell 1 (green) Area ("+cal.getUnit()+u"\u00b2"+")", t-1, cellAreas1[t])
        rt.setValue("Cell 1 Nucleus Area ("+cal.getUnit()+u"\u00b2"+")", t-1, nucleusAreas1[t])
        rt.setValue("Cell 1 All", t-1, cellValues1[t])
        rt.setValue("Cell 1 Nucleus", t-1, nucleusValues1[t])
        rt.setValue("Cell 1 Non-Nucleus", t-1, nonNucleusValues1[t])
    rt.show(imp.getTitle()+"-Results")

    dataset = DefaultXYDataset()
    dataset.addSeries( "Cell 0", [time[1:], cellValues0[1:]] )
    dataset.addSeries( "Cell 1", [time[1:], cellValues1[1:]] )
    dataset.addSeries( "Nucleus 0", [time[1:], nucleusValues0[1:]] )
    dataset.addSeries( "Nucleus 1", [time[1:], nucleusValues1[1:]] )
    dataset.addSeries( "Non-Nucleus 0", [time[1:], nonNucleusValues0[1:]] )
    dataset.addSeries( "Non-Nucleus 1", [time[1:], nonNucleusValues1[1:]] )

    chart = ChartFactory.createScatterPlot( imp.getTitle(), "Time ("+cal.getTimeUnit()+")", "Intensity Z", dataset, PlotOrientation.VERTICAL, True,True,False )
    plot = chart.getPlot()

    plot.setBackgroundPaint(Color(64, 128, 255))
    plot.setDomainGridlinePaint(Color.BLACK)
    plot.setRangeGridlinePaint(Color.BLACK)

    renderer = plot.getRenderer()
    legend = LegendItemCollection()
    shapeR = 2.0
    nucShape = Ellipse2D.Float(-shapeR,-shapeR,shapeR*2,shapeR*2)
    nonNucShape = Path2D.Float()
    nonNucShape.moveTo(-shapeR,-shapeR)
    nonNucShape.lineTo(shapeR,shapeR)
    nonNucShape.moveTo(shapeR,-shapeR)
    nonNucShape.lineTo(-shapeR,shapeR)
    for s in range(dataset.getSeriesCount()):

        if s == 0:
            renderer.setSeriesLinesVisible(s, True)
            renderer.setSeriesShapesVisible(s, False)
            renderer.setSeriesStroke(s, BasicStroke(1))
            renderer.setSeriesPaint(s, Color.RED)
            legend.add( LegendItem("Cell 0", Color.RED) )
        elif s == 1:
            renderer.setSeriesLinesVisible(s, True)
            renderer.setSeriesShapesVisible(s, False)
            renderer.setSeriesStroke(s, BasicStroke(1))
            renderer.setSeriesPaint(s, Color.GREEN)
            legend.add( LegendItem("Cell 1", Color.GREEN) )
        elif s == 2:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nucShape)
            renderer.setSeriesPaint(s, Color.RED)
        elif s == 3:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nucShape)
            renderer.setSeriesPaint(s, Color.GREEN)
        elif s == 4:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nonNucShape)
            renderer.setSeriesPaint(s, Color.RED)
        elif s == 5:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nonNucShape)
            renderer.setSeriesPaint(s, Color.GREEN)


    plot.setFixedLegendItems(legend)

    frame = ChartFrame(imp.getTitle()+" Z-Normalised Intensity", chart)
    frame.pack()
    frame.setSize( Dimension(800, 800) )
    frame.setLocationRelativeTo(None)
    frame.setVisible(True)
def computeRegistration():
    while atomicI.get() < nSections:
        l = atomicI.getAndIncrement()
        if l < nSections:
            IJ.log('Computing EM/LM registration for layer ' + str(l).zfill(4))

            layerFolder = fc.mkdir_p(
                os.path.join(registrationFolder, 'layer_' + str(l).zfill(4)))
            toRegisterFolder = fc.mkdir_p(
                os.path.join(layerFolder, 'toRegister'))
            registeredFolder = fc.mkdir_p(
                os.path.join(layerFolder, 'registered'))

            # Applying appropriate filters to make lowresEM and LM look similar for layer l
            imLM = IJ.openImage(imPaths['LM'][l])
            imLM = fc.localContrast(imLM)
            imLMPath = os.path.join(toRegisterFolder,
                                    'imLM_' + str(l).zfill(4) + '.tif')
            IJ.save(imLM, imLMPath)

            imEM = IJ.openImage(imPaths['EM'][l])
            imEM = fc.localContrast(imEM)
            imEM = fc.blur(imEM, 2)
            imEMPath = os.path.join(toRegisterFolder,
                                    'imEM_' + str(l).zfill(4) + '.tif')
            IJ.save(imEM, imEMPath)

            # Compute first a simple affine registration on the non-cropped images
            IJ.log(
                'Computing affine and moving least squares alignment for layer '
                + str(l).zfill(4))
            firstStepRegistered = False

            # registration at first step with 1step/octave (less features)
            pLowRes = getSIFTMatchingParameters(nOctaves[0], 1.6, 16, 4000, 8,
                                                4)

            featuresLM = getFeatures(imLMPath, pLowRes)
            featuresEM = getFeatures(imEMPath, pLowRes)

            matchingResults = getMatchingResults(featuresLM, featuresEM)
            if matchingResults is None:
                IJ.log(
                    'No registration matching at low resolution matching step 1 in layer '
                    + str(l).zfill(4))
            else:
                model, inliers = matchingResults
                distance = PointMatch.meanDistance(
                    inliers
                )  # mean displacement of the remaining matching features
                IJ.log('---Layer ' + str(l).zfill(4) + ' distance ' +
                       str(distance) + ' px with ' + str(len(inliers)) +
                       ' inliers')
                if distance > matchingThreshold[0]:
                    IJ.log(
                        'Matching accuracy is lower than the threshold at the low resolution step 1 - '
                        + str(l).zfill(4) + ' - distance - ' + str(distance))
                else:
                    affTransform = model.createAffine()
                    s1, s2 = getScalingFactors(affTransform)
                    IJ.log('Layer ' + str(l).zfill(4) +
                           ' scaling factors - step 1 - ' + str(s1) + ' - ' +
                           str(s2) + '--' + str(s1 * s2) + ' affDeterminant ' +
                           str(affTransform.getDeterminant()) + ' nInliers ' +
                           str(len(inliers)))
                    if (abs(s1 - 1) < 0.2) and (
                            abs(s2 - 1) < 0.2
                    ):  # scaling in both directions should be close to 1
                        IJ.log('First step ok - layer ' + str(l).zfill(4))
                        firstStepRegistered = True
                        loaderZ.serialize(
                            affTransform,
                            os.path.join(registeredFolder, 'affineSerialized'))

            if not firstStepRegistered:
                IJ.log(
                    'First step registration in layer ' + str(l).zfill(4) +
                    ' with few features has failed. Trying with more features.'
                )
                # registration at first step with 3steps/octave (more features)
                pLowRes = getSIFTMatchingParameters(3, 1.6, 64, 4000, 8, 4)
                #pLowRes = getSIFTMatchingParameters(nOctaves[0], 1.6, 16, 4000, 8, 4) # for BIB

                featuresLM = getFeatures(imLMPath, pLowRes)
                featuresEM = getFeatures(imEMPath, pLowRes)

                matchingResults = getMatchingResults(featuresLM, featuresEM)
                if matchingResults is None:
                    IJ.log(
                        'No registration matching at low resolution matching step 1bis in layer '
                        + str(l).zfill(4))
                else:
                    model, inliers = matchingResults
                    distance = PointMatch.meanDistance(
                        inliers
                    )  # mean displacement of the remaining matching features
                    IJ.log('---Layer ' + str(l).zfill(4) + ' distance ' +
                           str(distance) + ' px with ' + str(len(inliers)) +
                           ' inliers')
                    if distance > matchingThreshold[0]:
                        IJ.log(
                            'Matching accuracy is lower than the threshold at the high resolution step 1bis - '
                            + str(l).zfill(4) + ' - distance - ' +
                            str(distance))
                    else:
                        affTransform = model.createAffine()
                        s1, s2 = getScalingFactors(affTransform)
                        IJ.log('Layer ' + str(l).zfill(4) +
                               ' scaling factors - step 1bis - ' + str(s1) +
                               ' - ' + str(s2) + '--' + str(s1 * s2) +
                               ' affDeterminant ' +
                               str(affTransform.getDeterminant()) +
                               ' nInliers ' + str(len(inliers)))
                        if (abs(s1 - 1) < 0.2) and (
                                abs(s2 - 1) < 0.2
                        ):  # scaling in both directions should be close to 1
                            IJ.log('First step 1bis ok - layer ' +
                                   str(l).zfill(4))
                            firstStepRegistered = True
                            loaderZ.serialize(
                                affTransform,
                                os.path.join(registeredFolder,
                                             'affineSerialized'))

            if not firstStepRegistered:
                IJ.log('The two first step trials in layer ' +
                       str(l).zfill(4) + ' have failed')
            else:
                # Affine transform and crop the LM, and compute a high res MLS matching
                with lock:  # only one trakem working at a time
                    # apply affTransform
                    patch = Patch.createPatch(pZ, imLMPath)
                    layerZ.add(patch)
                    patch.setAffineTransform(affTransform)
                    patch.updateBucket()

                    # crop and export
                    bb = Rectangle(0, 0, widthEM, heightEM)
                    affineCroppedIm = loaderZ.getFlatImage(
                        layerZ, bb, 1, 0x7fffffff, ImagePlus.GRAY8, Patch,
                        layerZ.getAll(Patch), True, Color.black, None)
                    affineCroppedImPath = os.path.join(
                        toRegisterFolder,
                        'affineCroppedLM_' + str(l).zfill(4) + '.tif')
                    IJ.save(affineCroppedIm, affineCroppedImPath)
                    affineCroppedIm.close()

                    layerZ.remove(patch)
                    layerZ.recreateBuckets()

                pHighRes = getSIFTMatchingParameters(nOctaves[1], 1.6, 64,
                                                     4096, 8, 4)
                featuresLM = getFeatures(affineCroppedImPath, pHighRes)
                featuresEM = getFeatures(imEMPath, pHighRes)

                # get the MLS
                matchingResults = getMatchingResults(featuresLM, featuresEM)
                if matchingResults is None:
                    IJ.log(
                        'It cannot be, there should be a good match given that an affine was computed. Layer '
                        + str(l).zfill(4))
                else:
                    model, inliers = matchingResults
                    affTransform = model.createAffine()
                    s1, s2 = getScalingFactors(affTransform)
                    IJ.log('Second step determinant - layer ' +
                           str(l).zfill(4) + ' - determinant - ' +
                           str(affTransform.getDeterminant()) + ' nInliers ' +
                           str(len(inliers)) + 'Scaling factors - step 2 - ' +
                           str(s1) + ' - ' + str(s2))
                    if (abs(s1 - 1) < 0.2) and (abs(s2 - 1) < 0.2) and len(
                            inliers
                    ) > 50:  # scaling in both directions should be close to 1
                        distance = PointMatch.meanDistance(
                            inliers
                        )  # mean displacement of the remaining matching features
                        if distance > matchingThreshold[1]:
                            IJ.log(
                                'Weird: matching accuracy is lower than the threshold at the high resolution step 2 - '
                                + str(l).zfill(4) + ' - distance - ' +
                                str(distance))
                        else:
                            mlst = MovingLeastSquaresTransform()
                            mlst.setModel(AffineModel2D)
                            mlst.setAlpha(1)
                            mlst.setMatches(inliers)

                            xmlMlst = mlst.toXML('\t')
                            with open(
                                    os.path.join(registeredFolder, 'MLST.xml'),
                                    'w') as f:
                                f.write(xmlMlst)

                            loaderZ.serialize(
                                mlst,
                                os.path.join(registeredFolder,
                                             'mlstSerialized'))

                            registrationStats.append(
                                [l, distance, len(inliers)])
from java.awt import MouseInfo, Rectangle
from java.util.concurrent import Executors, TimeUnit
import sys

region = Rectangle(500, 500, 400, 400)
outside = True


def regionEntered():
    global outside
    try:
        point = MouseInfo.getPointerInfo().getLocation()
        print point
        if region.contains(point):
            if outside:
                print "ENTERED REGION"
                outside = False
        else:
            if not outside:
                print "EXITED REGION"
                outside = True
    except Exception as e:
        print sys.print_exception(e)


scheduler = Executors.newSingleThreadScheduledExecutor()
scheduler.scheduleAtFixedRate(regionEntered, 0, 100, TimeUnit.MILLISECONDS)
matrix.set(0, ndims, rot2d.getTranslateX())
matrix.set(1, 0, rot2d.getShearY())
matrix.set(1, 1, rot2d.getScaleY())
matrix.set(1, ndims, rot2d.getTranslateY())
for i in range(2, img.numDimensions()):
  matrix.set(i, i, 1.0)

from pprint import pprint
pprint([list(row) for row in matrix.getArray()])

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

# View the image rotated, without enlarging the canvas
minC = [0 for i in range(img.numDimensions())]
maxC = [img.dimension(i) -1 for i in range(img.numDimensions())]
imgRot2d = IL.wrap(Views.interval(rotated, minC, maxC), imp.getTitle() + " - rot2d")
imgRot2d.show()

# View the image rotated, enlarging the canvas to fit it.
# We compute the bounds of the enlarged canvas by transforming a rectangle, 
# then define the interval min and max coordinates by subtracting 
# and adding as appropriate to exactly capture the complete rotated image.
bounds = rot2d.createTransformedShape(Rectangle(img.dimension(0), img.dimension(1))).getBounds()
minC[0] = (img.dimension(0) - bounds.width) / 2
minC[1] = (img.dimension(1) - bounds.height) / 2
maxC[0] += abs(minC[0]) -1
maxC[1] += abs(minC[1]) -1
imgRot2dFit = IL.wrap(Views.interval(rotated, minC, maxC), imp.getTitle() + " - rot2dFit")
imgRot2dFit.show()
Ejemplo n.º 28
0
registrationFolder = os.path.join(os.path.dirname(projectPath),
                                  'LMEMRegistration')

for idChannel, channel in enumerate(channels):
    affineCroppedFolder = os.path.join(LMFolder, 'affineCropped_' + channel)

    # the dimensions of the first affineCropped determine the size of the layerset of the trakem project (and for the export)
    firstImagePath = os.path.join(affineCroppedFolder,
                                  os.walk(affineCroppedFolder).next()[2][0])
    im0 = IJ.openImage(firstImagePath)
    width0 = im0.getWidth()
    height0 = im0.getHeight()
    im0.close()

    roiExport = Rectangle(0, 0, width0, height0)

    projectPath = os.path.join(EMFolder, 'LMProject_' + channel + '.xml')
    p, loader, layerset, nLayers = fc.getProjectUtils(
        fc.initTrakem(LMFolder, nLayers))
    p.saveAs(projectPath, True)
    layerset.setDimensions(0, 0, width0, height0)

    for l, layer in enumerate(layerset.getLayers()):
        layerFolder = os.path.join(registrationFolder,
                                   'layer_' + str(l).zfill(4))
        registeredFolder = os.path.join(layerFolder, 'registered')
        MLSTPath = os.path.join(registeredFolder, 'MLST.xml')
        if os.path.isfile(MLSTPath):
            MLSTransform = CoordinateTransformXML().parse(MLSTPath)
            affineCroppedImPath = os.path.join(
Ejemplo n.º 29
0
def specifyRoiUI(roi=Roi(0, 0, 0, 0)):
    # A panel in which to place UI elements
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
    gb = GridBagLayout()
    panel.setLayout(gb)
    gc = GBC()

    bounds = roi.getBounds() if roi else Rectangle()
    textfields = []
    roimakers = []

    # Basic properties of most UI elements, will edit when needed
    gc.gridx = 0  # can be any natural number
    gc.gridy = 0  # idem.
    gc.gridwidth = 1  # when e.g. 2, the UI element will occupy two horizontally adjacent grid cells
    gc.gridheight = 1  # same but vertically
    gc.fill = GBC.NONE  # can also be BOTH, VERTICAL and HORIZONTAL

    for title in ["x", "y", "width", "height"]:
        # label
        gc.gridx = 0
        gc.anchor = GBC.EAST
        label = JLabel(title + ": ")
        gb.setConstraints(label, gc)  # copies the given constraints 'gc',
        # so we can modify and reuse gc later.
        panel.add(label)
        # text field, below the title
        gc.gridx = 1
        gc.anchor = GBC.WEST
        text = str(getattr(bounds,
                           title))  # same as e.g. bounds.x, bounds.width, ...
        textfield = JTextField(text,
                               10)  # 10 is the size of the field, in digits
        gb.setConstraints(textfield, gc)
        panel.add(textfield)
        textfields.append(
            textfield)  # collect all 4 created textfields for the listeners
        # setup ROI and text field listeners
        listener = RoiMaker(textfields,
                            len(textfields) -
                            1)  # second argument is the index of textfield
        # in the list of textfields.
        roimakers.append(listener)
        textfield.addKeyListener(listener)
        textfield.addMouseWheelListener(listener)
        # Position next ROI property in a new row by increasing the Y coordinate of the layout grid
        gc.gridy += 1

    # User documentation (uses HTML to define line breaks)
    doc = JLabel(
        "<html><body><br />Click on a field to activate it, then:<br />" +
        "Type in integer numbers<br />" +
        "or use arrow keys to increase by 1<br />" +
        "or use the scroll wheel on a field.</body></html>")
    gc.gridx = 0  # start at the first column
    gc.gridwidth = 2  # Spans both columns
    gb.setConstraints(doc, gc)
    panel.add(doc)

    # Listen to changes in the ROI of imp
    roilistener = TextFieldUpdater(textfields)
    Roi.addRoiListener(roilistener)

    # Show window
    frame = JFrame("Specify rectangular ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setLocationRelativeTo(None)  # center in the screen
    frame.setDefaultCloseOperation(
        JFrame.DO_NOTHING_ON_CLOSE)  # prevent closing the window
    frame.addWindowListener(
        CloseControl(roilistener))  # handles closing the window
    frame.setVisible(True)
Ejemplo n.º 30
0
from java.awt import MouseInfo, Rectangle, Toolkit
from java.util.concurrent import Executors, TimeUnit
import sys
from ij import IJ

# Dimensions of an action region
w, h = 50, 50
# Dimensions of the whole screen
screen = Toolkit.getDefaultToolkit().getScreenSize()

# Dictionary of action region names vs. tuple of area and ImageJ command with macro arguments
corners = {
    'top-left': (Rectangle(0, 0, w, h), ["Capture Screen"]),
    'top-right': (Rectangle(screen.width - w, 0, w, h), ["Split Channels"]),
    'bottom-right':
    (Rectangle(screen.width - w, screen.height - h, w,
               h), ["Z Project...", "projection=[Max Intensity]"]),
    'bottom-left': (Rectangle(0, screen.height - h, w,
                              h), ["Dynamic ROI Profiler"])
}

# State: whether the mouse is outside any of the action regions
outside = True


def actionRegion():
    global outside  # will be modified, so import for editing with 'global'
    try:
        point = MouseInfo.getPointerInfo().getLocation()
        inside = False
        # Check if the mouse is in any of the action regions