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 outputFiles(self, filename, attachLogo=False, logoText=None): rendered = self.getTarget().screenshot() if attachLogo: from java.awt.image import BufferedImage from com.raytheon.uf.common.localization import PathManagerFactory noaa = 'pyViz/logos/noaalogo2.png' nws = 'pyViz/logos/nwslogo.png' pathMgr = PathManagerFactory.getPathManager() noaa = pathMgr.getStaticFile(noaa) nws = pathMgr.getStaticFile(nws) noaaImage = ImageIO.read(noaa) nwsImage = ImageIO.read(nws) height = rendered.getHeight() + noaaImage.getHeight() finalBuf = BufferedImage(rendered.getWidth(), height, BufferedImage.TYPE_INT_ARGB) graphics = finalBuf.createGraphics() graphics.drawImage(rendered, 0, 0, None) graphics.drawImage(noaaImage, 0, rendered.getHeight(), None) graphics.fillRect(noaaImage.getWidth(), rendered.getHeight(), rendered.getWidth() - noaaImage.getWidth() - nwsImage.getWidth(), rendered.getHeight()) if logoText is not None: from java.awt import Color from com.raytheon.uf.viz.core.font import FontAdapter graphics.setColor(Color.BLACK) graphics.setFont(FontAdapter.getAWTFont(self.getTarget().getDefaultFont())) fm = graphics.getFontMetrics() textBounds = fm.getStringBounds(logoText, graphics) graphics.drawString(logoText, int((rendered.getWidth() - textBounds.getWidth()) / 2), \ int(rendered.getHeight() + (noaaImage.getHeight() / 2) + textBounds.getHeight() / 2)) graphics.drawImage(nwsImage, finalBuf.getWidth() - nwsImage.getWidth(), rendered.getHeight(), None) finalBuf.flush() self.outputImage(finalBuf, filename) else: self.outputImage(rendered, filename)
def outputFiles(self, filename, attachLogo=False, logoText=None): rendered = self.getTarget().screenshot() if attachLogo: from java.awt.image import BufferedImage noaa = File(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logos/noaalogo2.png')) nws = File(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logos/nwslogo.png')) noaaImage = ImageIO.read(noaa) nwsImage = ImageIO.read(nws) height = rendered.getHeight() + noaaImage.getHeight() finalBuf = BufferedImage(rendered.getWidth(), height, BufferedImage.TYPE_INT_ARGB) graphics = finalBuf.createGraphics() graphics.drawImage(rendered, 0, 0, None) graphics.drawImage(noaaImage, 0, rendered.getHeight(), None) graphics.fillRect(noaaImage.getWidth(), rendered.getHeight(), rendered.getWidth() - noaaImage.getWidth() - nwsImage.getWidth(), rendered.getHeight()) if logoText is not None: from java.awt import Color graphics.setColor(Color.BLACK) graphics.setFont(self.getAWTFont(self.getTarget().getDefaultFont())) fm = graphics.getFontMetrics() textBounds = fm.getStringBounds(logoText, graphics) graphics.drawString(logoText, int((rendered.getWidth() - textBounds.getWidth()) / 2), \ int(rendered.getHeight() + (noaaImage.getHeight() / 2) + textBounds.getHeight() / 2)) graphics.drawImage(nwsImage, finalBuf.getWidth() - nwsImage.getWidth(), rendered.getHeight(), None) finalBuf.flush() self.outputImage(finalBuf, filename) else: self.outputImage(rendered, filename)
def run(self): try: bounds = self.layer.getMinimalBoundingBox(Patch, True) filepath = os.path.join( self.target_dir, "section-" + str(self.i).zfill(5) + "-[x=" + str(bounds.x) + "-y=" + str(bounds.y) + "-width=" + str(bounds.width) + "-height=" + str(bounds.height) + "].zip") if os.path.exists(filepath): System.out.println("Skipping: " + filepath) return # Export System.out.println("Preparing: " + os.path.split(filepath)[1]) img = self.layer.getProject().getLoader().getFlatAWTImage( self.layer, bounds, 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() g.drawImage(img, 0, 0, None) g.dispose() g = None imp = ImagePlus(str(self.layer.getZ()), ByteProcessor(bi)) FileSaver(imp).saveAsZip(filepath) bi.flush() bi = None imp.flush() imp = None ip = None System.out.println("Saved: " + os.path.split(filepath)[1]) except: import sys e = sys.exc_info() System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" + str(e[2]))
def run(title): gd = GenericDialog("Record Window") gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.") gd.addNumericField("Max. frames:", 50, 0) gd.addNumericField("Milisecond interval:", 300, 0) gd.addSlider("Start in (seconds):", 0, 20, 5) frames = [] titles = [] for f in Frame.getFrames(): if f.isEnabled() and f.isVisible(): frames.append(f) titles.append(f.getTitle()) gd.addChoice("Window:", titles, titles[0]) gd.addCheckbox("To file", False) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds frame = frames[gd.getNextChoiceIndex()] delay = int(gd.getNextNumber()) tofile = gd.getNextBoolean() dir = None if tofile: dc = DirectoryChooser("Directory to store image frames") dir = dc.getDirectory() if dir is None: return # dialog canceled snaps = [] borders = None executors = Executors.newFixedThreadPool(1) try: while delay > 0: IJ.showStatus("Starting in " + str(delay) + "s.") time.sleep(1) # one second delay -= 1 IJ.showStatus("Capturing frame borders...") bounds = frame.getBounds() robot = Robot() frame.toFront() time.sleep(0.5) # half a second borders = robot.createScreenCapture(bounds) IJ.showStatus("Recording " + frame.getTitle()) # Set box to the inside borders of the frame insets = frame.getInsets() box = bounds.clone() box.x = insets.left box.y = insets.top box.width -= insets.left + insets.right box.height -= insets.top + insets.bottom start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 i = 1 fus = None if tofile: fus = [] # 0 n_frames means continuous acquisition while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval): now = System.currentTimeMillis() / 1000.0 # in seconds real_interval = now - last if real_interval >= interval: last = now img = snapshot(frame, box) if tofile: fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets))) # will flush img i += 1 else: snaps.append(img) intervals.append(real_interval) else: time.sleep(interval / 5) # interrupt capturing: if IJ.escapePressed(): IJ.showStatus("Recording user-interrupted") break # debug: # print "insets:", insets # print "bounds:", bounds # print "box:", box # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight() # Create stack stack = None if tofile: for fu in snaps: fu.get() # wait on all stack = VirtualStack(bounds.width, bounds.height, None, dir) files = File(dir).list(TifFilter()) Arrays.sort(files) for f in files: stack.addSlice(f) else: stack = ImageStack(bounds.width, bounds.height, None) t = 0 for snap, real_interval in zip(snaps, intervals): bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB) g = bi.createGraphics() g.drawImage(borders, 0, 0, None) g.drawImage(snap, insets.left, insets.top, None) stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor()) t += real_interval snap.flush() bi.flush() borders.flush() ImagePlus(frame.getTitle() + " recording", stack).show() IJ.showStatus("Done recording " + frame.getTitle()) except Exception, e: print "Some error ocurred:" print e.printStackTrace() IJ.showStatus("") if borders is not None: borders.flush() for snap in snaps: snap.flush()
def run(title): gd = GenericDialog('Record Window') gd.addMessage( "Maximum number of frames to record.\nZero means infinite, interrupt with ESC key." ) gd.addNumericField('Max. frames:', 50, 0) gd.addNumericField('Milisecond interval:', 300, 0) gd.addSlider('Start in (seconds):', 0, 20, 5) frames = [] titles = [] for f in Frame.getFrames(): if f.isEnabled() and f.isVisible(): frames.append(f) titles.append(f.getTitle()) gd.addChoice('Window:', titles, titles[0]) gd.addCheckbox("To file", False) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds frame = frames[gd.getNextChoiceIndex()] delay = int(gd.getNextNumber()) tofile = gd.getNextBoolean() dir = None if tofile: dc = DirectoryChooser("Directory to store image frames") dir = dc.getDirectory() if dir is None: return # dialog canceled snaps = [] borders = None executors = Executors.newFixedThreadPool(1) try: while delay > 0: IJ.showStatus('Starting in ' + str(delay) + 's.') time.sleep(1) # one second delay -= 1 IJ.showStatus('Capturing frame borders...') bounds = frame.getBounds() robot = Robot() frame.toFront() time.sleep(0.5) # half a second borders = robot.createScreenCapture(bounds) IJ.showStatus("Recording " + frame.getTitle()) # Set box to the inside borders of the frame insets = frame.getInsets() box = bounds.clone() box.x = insets.left box.y = insets.top box.width -= insets.left + insets.right box.height -= insets.top + insets.bottom start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 i = 1 fus = None if tofile: fus = [] # 0 n_frames means continuous acquisition while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval): now = System.currentTimeMillis() / 1000.0 # in seconds real_interval = now - last if real_interval >= interval: last = now img = snapshot(frame, box) if tofile: fus.append( executors.submit( Saver(i, dir, bounds, borders, img, insets))) # will flush img i += 1 else: snaps.append(img) intervals.append(real_interval) else: time.sleep(interval / 5) # interrupt capturing: if IJ.escapePressed(): IJ.showStatus("Recording user-interrupted") break # debug: #print "insets:", insets #print "bounds:", bounds #print "box:", box #print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight() # Create stack stack = None if tofile: for fu in snaps: fu.get() # wait on all stack = VirtualStack(bounds.width, bounds.height, None, dir) files = File(dir).list(TifFilter()) Arrays.sort(files) for f in files: stack.addSlice(f) else: stack = ImageStack(bounds.width, bounds.height, None) t = 0 for snap, real_interval in zip(snaps, intervals): bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB) g = bi.createGraphics() g.drawImage(borders, 0, 0, None) g.drawImage(snap, insets.left, insets.top, None) stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus('', bi).getProcessor()) t += real_interval snap.flush() bi.flush() borders.flush() ImagePlus(frame.getTitle() + " recording", stack).show() IJ.showStatus('Done recording ' + frame.getTitle()) except Exception, e: print "Some error ocurred:" print e.printStackTrace() IJ.showStatus('') if borders is not None: borders.flush() for snap in snaps: snap.flush()
from ij.process import ColorProcessor from java.awt.image import BufferedImage as BI from java.lang import Thread f = ImagePlus.getDeclaredField("listeners") f.setAccessible(True) listeners = f.get(None) imp = IJ.getImage() canvas = imp.getWindow().getCanvas() # Define range of slices to capture slices = xrange(1, imp.getNSlices() + 1) w, h = canvas.getWidth(), canvas.getHeight() capture = ImageStack(w, h) for i in slices: imp.setSlice(i) for l in listeners: l.imageUpdated(imp) Thread.sleep(50) # wait for repaints to happen, triggered by listeners, if any. bi = BI(w, h, BI.TYPE_INT_ARGB) g = bi.createGraphics() canvas.paint(g) g.dispose() capture.addSlice(ColorProcessor(bi)) bi.flush() ImagePlus("capture", capture).show()