def run(title): gd = 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.showStatus('Starting in ' + str(delay) + 's.') time.sleep(1) # one second delay -= 1 IJ.showStatus('') System.out.println("Starting...") # start capturing robot = Robot() box = Rectangle(IJ.getScreenSize()) start = System.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 = System.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 System.out.println("End") awt = snaps[0] stack = ImageStack(awt.getWidth(None), awt.getHeight(None), None) t = 0 for snap, real_interval in zip(snaps, intervals): stack.addSlice(str(IJ.d2s(t, 3)), 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 run(title): gd = 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.showStatus("Starting in " + str(delay) + "s.") time.sleep(1) # one second delay -= 1 IJ.showStatus("") System.out.println("Starting...") # start capturing robot = Robot() box = Rectangle(IJ.getScreenSize()) start = System.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 = System.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 System.out.println("End") awt = snaps[0] stack = ImageStack(awt.getWidth(None), awt.getHeight(None), None) t = 0 for snap, real_interval in zip(snaps, intervals): stack.addSlice(str(IJ.d2s(t, 3)), 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 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 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 array import array from ij import IJ from ij.measure.CurveFitter import * # Example from # http://rsbweb.nih.gov/ij/macros/examples/CurveFittingDemo.txt # x = array('d', [0, 1, 2, 3, 4, 5]) # y = array('d', [0, 0.9, 4.5, 8, 18, 24]) # # make one where I know approximate coefficients x = array("d", [0, 1, 2, 3, 4, 5]) y = array("d", [0, 1.1, 1.9, 2.95, 4.02, 4.99]) cf = CurveFitter(x, y) cf.doFit(STRAIGHT_LINE) res = cf.getParams() # N.B. cf.getParams() returns # [ intercept, slope, sum of square residuals] b = res[0] m = res[1] p3 = res[2] print "Linear fit example: b=" + IJ.d2s(b, 6) + ", m =" + IJ.d2s(m, 6) + ", par3=" + IJ.d2s(p3, 6) print cf.getResultString()
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()
# print(strFile) imp = IJ.openImage(strFile) imp.setTitle(strName) imp.show() IJ.run("32-bit"); IJ.run("FD Math...", strMath) IJ.selectWindow(strName) IJ.run("Close") IJ.selectWindow("Result") imp=WM.getCurrentImage() ip = imp.getProcessor() options = IM.MEAN | IM.MEDIAN | IM.MIN_MAX | IM.STD_DEV stats = IS.getStatistics(ip, options, imp.getCalibration()) if bVerbose: print " Min:", IJ.d2s(stats.min,2) print " Man:", IJ.d2s(stats.max,2) print " Mean:", IJ.d2s(stats.mean,2) print "Std Dev:" , IJ.d2s(stats.stdDev,2) delta = stats.max - stats.min pixels = ip.getPixels() newPixels = map(lambda x: (x - stats.min)/delta, pixels) ipSub = FloatProcessor(ip.width, ip.height, newPixels, None) impSub = ImagePlus("Sub", ipSub) impSub.show() IJ.selectWindow("Result") IJ.run("Close") IJ.selectWindow("Sub") imp=WM.getCurrentImage() imp.setTitle(strName+"-acf")