def __init__(self, *arg): """ Return Rect that is subclassed from java.awt.Rectangle. Alternative arguments: * x, y, width, height * (x, y), (width, height) * (x, y, width, height) * Rect * Obj with rect attribute Rect has the attributes:: x, y, width, height top, left, bottom, right topleft, bottomleft, topright, bottomright midtop, midleft, midbottom, midright center, centerx, centery size, w, h Module initialization places pyj2d.Rect in module's namespace. """ def unpack(arg, lst=[]): for x in arg: if not isinstance(x, tuple): lst.append(x) else: lst = unpack(x, lst) return lst try: x = arg[0] y = arg[1] w = arg[2] h = arg[3] except IndexError: try: x = arg[0][0] y = arg[0][1] w = arg[0][2] h = arg[0][3] except (IndexError, TypeError, AttributeError): arg = unpack(arg) try: x = arg[0] y = arg[1] w = arg[2] h = arg[3] except IndexError: if hasattr(arg[0], 'rect'): arg[0] = arg[0].rect x = arg[0].x y = arg[0].y w = arg[0].width h = arg[0].height try: Rectangle.__init__(self, x, y, w, h) except TypeError: Rectangle.__init__(self, int(x), int(y), int(w), int(h))
def __init__(self, *arg): """ Return Rect that is subclassed from java.awt.Rectangle. Alternative arguments: * x,y,w,h * (x,y),(w,h) * (x,y,w,h) * Rect * Obj with rect attribute Rect has the attributes:: x, y, width, height Additional Rect attributes:: top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, w, h. Module initialization places pyj2d.Rect in module's namespace. """ def unpack(arg, lst=[]): for x in arg: if not isinstance(x, tuple): lst.append(x) else: lst = unpack(x, lst) return lst try: x,y,w,h = arg[0], arg[1], arg[2], arg[3] except IndexError: try: x,y,w,h = arg[0][0], arg[0][1], arg[0][2], arg[0][3] except (IndexError, TypeError, AttributeError): arg = unpack(arg) try: x,y,w,h = arg[0], arg[1], arg[2], arg[3] except IndexError: if hasattr(arg[0], 'rect'): arg[0] = arg[0].rect x,y,w,h = arg[0].x, arg[0].y, arg[0].width, arg[0].height try: Rectangle.__init__(self, x, y, w, h) except TypeError: Rectangle.__init__(self, int(x), int(y), int(w), int(h))
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}
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}
def union_ip(self, rect): """ Change this rect to represent the union of rect and this rect. """ r = Rectangle.union(self, rect) self.setLocation(r.x, r.y) self.setSize(r.width, r.height) return None
def unionall(self, rect_list): """ Return Rect representing the union of rect list and this rect. """ r = self for rect in rect_list: r = Rectangle.union(r, rect) return Rect(r.x, r.y, r.width, r.height)
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]))
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
def unionall_ip(self, rect_list): """ Change this rect to represent the union of rect list and this rect. """ r = self for rect in rect_list: r = Rectangle.union(r, rect) self.setLocation(r.x, r.y) self.setSize(r.width, r.height) return None
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()
def __init__(self, *arg): """ Return Rect that is subclassed from java.awt.Rectangle. Alternative arguments: * x,y,w,h * (x,y),(w,h) * (x,y,w,h) * Rect * Obj with rect attribute Rect has the attributes:: x, y, width, height Additional Rect attributes:: top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, w, h. Module initialization places pyj2d.Rect in module's namespace. """ try: x, y, w, h = arg[0], arg[1], arg[2], arg[3] except IndexError: try: x, y, w, h = arg[0].rect.x, arg[0].rect.y, arg[ 0].rect.width, arg[0].rect.height except AttributeError: try: x, y, w, h = arg[0].x, arg[0].y, arg[0].width, arg[ 0].height except AttributeError: try: x, y, w, h = arg[0][0], arg[0][1], arg[1][0], arg[1][1] except IndexError: x, y, w, h = arg[0][0], arg[0][1], arg[0][2], arg[0][3] try: Rectangle.__init__(self, x, y, w, h) except TypeError: Rectangle.__init__(self, int(x), int(y), int(w), int(h))
def __init__(self, *arg): """ Return Rect that is subclassed from java.awt.Rectangle. Alternative arguments: * x,y,w,h * (x,y),(w,h) * (x,y,w,h) * Rect * Obj with rect attribute Rect has the attributes:: x, y, width, height Additional Rect attributes:: top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, w, h. Module initialization places pyj2d.Rect in module's namespace. """ try: x,y,w,h = arg[0], arg[1], arg[2], arg[3] except IndexError: try: x,y,w,h = arg[0].rect.x, arg[0].rect.y, arg[0].rect.width, arg[0].rect.height except AttributeError: try: x,y,w,h = arg[0].x, arg[0].y, arg[0].width, arg[0].height except AttributeError: try: x,y,w,h = arg[0][0], arg[0][1], arg[1][0], arg[1][1] except IndexError: x,y,w,h = arg[0][0], arg[0][1], arg[0][2], arg[0][3] try: Rectangle.__init__(self, x, y, w, h) except TypeError: Rectangle.__init__(self, int(x), int(y), int(w), int(h))
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))
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)
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"
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)
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
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)
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
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)
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()
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
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)
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))
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]
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()),
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()
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()
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 union(self, rect): """ Return Rect representing the union of rect and this rect. """ r = Rectangle.union(self, rect) return Rect(r.x, r.y, r.width, r.height)
def __init__(self): Rectangle.__init__(self, 6, 7)
def diagrambuttonPressed(event) : IJ.showMessage("Push 'Auto' button each time you want to see the diagram") x1=10 y1=20 x2=100 y2=50 x3=60 y3=30 xr=10 yr=20 wr=20 hr=20 rect=Rectangle(xr,yr,wr,hr) #img=IJ.getImage() #nbslices=self.__img.getImageStackSize() nbslices=self.__maxLife IJ.run("Hyperstack...", "title=Diagram type=32-bit display=Color width="+str(x2+(nbslices+1)*x3)+" height="+str(y2+y3*len(dico))+" channels=1 slices="+str(len(self.__measures))+" frames=1") im=IJ.getImage() ip=im.getProcessor() for i in range(len(self.__measures)) : indiceligne=0 maxvalue=0 minvalue=1000000 im.setPosition(1,i+1,1) for cellname in self.__listcellname : indiceligne+=1 for indicecolonne in range(1,nbslices+1): rect.setLocation(x2+indicecolonne*x3+int(x3/6),(y1+indiceligne*y3-int(y3/2))) # we create at the first iteration a dictionary with the rectangles (for a future use) if i==0 : self.__gridrectangle[(indiceligne,indicecolonne)]=Rectangle(rect) im.setRoi(rect) ipr=im.getProcessor() # we find the min and max values of the datas for a measure given. if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]>maxvalue : maxvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1] if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]<minvalue : minvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1] # we fill the rectangle with the value of the measure ipr.setValue(self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]) ipr.fill() # we write the names and the n of slices on the image with the maxvalue. ip.setValue(maxvalue) ip.moveTo(x1,y1) ip.drawString(self.__measures[i]) for j in range(1,nbslices+1) : ip.moveTo(x2+j*x3,y1) ip.drawString("Slice "+str(j)) j=0 for cellname in self.__listcellname : ip.moveTo(x1,y2+j*y3) ip.drawString(cellname) j+=1 im.killRoi() im=IJ.run(im,"Fire","") IJ.run("Brightness/Contrast...", "") #im.setMinAndMax(minvalue,maxvalue) #im.updateImage() #we add a mouse listener in order to be able to show the roi corresponding to a rectangle when the user clicks on it. listener = ML() listener.name=imgName for imp in map(WindowManager.getImage, WindowManager.getIDList()): if imp.getTitle().startswith("Diagram") : win = imp.getWindow() if win is None: continue win.getCanvas().addMouseListener(listener)
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)])