def delete(imp, roiMan, roiTotal): # set results table rt = ResultsTable.getResultsTable() # set up analyzer analyzer = Analyzer(imp, 1, rt) totalPixels = 0 # Set the color and line options for erasing IJ.run("Colors...", "foreground=black background=black selection=magenta") if roiMan is not None: # Iterate through the ROIs for roi in xrange(roiTotal): # Select the ROI roiMan.select(roi) selectRoi = roiMan.getRoi(roi) # measure analyzer.measure() meas = rt.getRowAsString(0) newLine = meas.split(" ", 1) pixels = float(newLine[1]) totalPixels = totalPixels + pixels # Tag the ROI IJ.run(imp, "Fill", "slice") # end for loop return totalPixels else: return 0
def learn(imp): IJ.run(imp, "Line Width...", "line=10") IJ.run("Colors...", "foreground=black background=black selection=red") # Clear ROI manager roiMan = RoiManager.getInstance() if roiMan is not None: roiMan.reset() # set results table rt = ResultsTable.getResultsTable() # set up analyzer analyzer = Analyzer(imp, 1, rt) impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "8-bit", "") IJ.run(impBrightness, "Auto Threshold", "method=Shanbhag white") IJ.run(impBrightness, "Analyze Particles...", "size=50000-Infinity circularity=0.00-1.00 show=Masks add in_situ") # Pixel running total pixelTotal = zeros('f', 4) roiTotal = roiMan.getCount() if roiMan is not None: # Iterate throught the ROIs for roi in xrange(roiTotal): roiMan.select(roi) selectRoi = roiMan.getRoi(roi) option = getOptions() # measure analyzer.measure() meas = rt.getRowAsString(0) newLine = meas.split(" ", 1) pixels = float(newLine[1]) # Tag the ROI IJ.run(imp, "Fill", "slice") pixelTotal[0] = pixelTotal[0] + (option[0] * pixels) pixelTotal[1] = pixelTotal[1] + (option[1] * pixels) pixelTotal[2] = pixelTotal[2] + (option[2] * pixels) pixelTotal[3] = pixelTotal[3] + (option[3] * pixels) return pixelTotal else: return pixelTotal
def identifyCoralline(imp): # Prepare Roi Manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # set results table rt = ResultsTable.getResultsTable() impTemp = imp.duplicate() IJ.run(impTemp, "8-bit", "") # convert to 8-bit impCoralline = TH.whiteThreshold(impTemp) impTemp.close() IJ.run(impCoralline, "Analyze Particles...", "size=10000-Infinity circularity=0-0.50 show=Masks add in_situ") analyzer = Analyzer(imp, 1, rt) analyzer.measure() meas = rt.getRowAsString(0) newLine = meas.split(" ", 1) coralline = float(newLine[1]) return coralline
show = sys.argv[-8] display_results = sys.argv[-7] == "yes" all_results = sys.argv[-6] == "yes" exclude_edges = sys.argv[-5] == "yes" include_holes = sys.argv[-4] == "yes" output_filename = sys.argv[-3] output_datatype = sys.argv[-2] results_path = sys.argv[-1] # Open the input image file. input_image_plus = IJ.openImage(input_file) # Create a copy of the image. input_image_plus_copy = input_image_plus.duplicate() image_processor_copy = input_image_plus_copy.getProcessor() analyzer = Analyzer(input_image_plus_copy) # Set binary options. options_list = OPTIONS if black_background: options_list.append("black") options = " ".join(options_list) IJ.run(input_image_plus_copy, "Options...", options) if not image_processor_copy.isBinary(): # Convert the image to binary grayscale. IJ.run(input_image_plus_copy, "Make Binary", "") # Set the options. options = ['size=%s' % size] circularity_str = '%.3f-%.3f' % (circularity_min, circularity_max)
# FINDS THE TISSUE AREA img2 = imp.duplicate() channels2=ChannelSplitter.split(img2); redimg2=channels2[0]; IJ.run(redimg2, "8-bit", ""); IJ.setAutoThreshold(redimg2, "Default dark"); IJ.setThreshold(redimg2,20, 254); IJ.run(redimg2, "Convert to Mask", ""); redimg2.show() time.sleep(1) rt2 = ResultsTable() ta=Analyzer(redimg2,Measurements.AREA|Measurements.LIMIT,rt2) ta.measure(); double=rt2.getColumnAsDoubles(rt2.getColumnIndex("Area")) summary["Tissue-area"] =double[0]; redimg2.changes = False redimg2.close() # PARTICLE ANALYSIS ETC.. channels = ChannelSplitter.split(imp); for i, channel in enumerate(channels): IJ.setAutoThreshold(channel,"Default");
def Measurements(channels, timelist, dirs, parameters): """ Takes measurements of weka selected ROIs in a generated aligned image stack. """ # Set desired measurements. an = Analyzer() an.setMeasurements(an.AREA + an.MEAN + an.MIN_MAX + an.SLICE) # Opens raw-projections as stack. test = IJ.run("Image Sequence...", "open=" + dirs["Aligned_All"] + " number=400 starting=1 increment=1 scale=400 file=.tif sort") # Calls roimanager. rm = RoiManager.getInstance() total_rois = rm.getCount() # Deletes artefact ROIs (too large or too small). imp = WindowManager.getCurrentImage() for roi in reversed(range(total_rois)): rm.select(roi) size = imp.getStatistics().area if size < int(float(parameters["cell_min"])): rm.select(roi) rm.runCommand('Delete') elif size > int(float(parameters["cell_max"])): rm.select(roi) rm.runCommand('Delete') else: rm.runCommand("Deselect") # Confirm that ROI selection is Ok (comment out for headless run). WaitForUserDialog("ROI check", "Control ROI selection, then click OK").show() # Measure each ROI for each channel. imp = WindowManager.getCurrentImage() rm.runCommand("Select All") rm.runCommand("multi-measure measure_all One row per slice") # Close. imp = WindowManager.getCurrentImage() imp.close() # Get measurement results. rt = ResultsTable.getResultsTable() Area = rt.getColumn(0) Mean = rt.getColumn(1) Slice = rt.getColumn(27) # Removes (and counts) artefact ROIs (redundant) # Area indices without outliers Area_indices = [index for (index, value) in enumerate(Area, start=0) if value > 0 and value < 9999999] # Mean without outliers from area (redundant) Filtered_mean = [Mean[index] for index in Area_indices] Filtered_slice = [Slice[index] for index in Area_indices] # Number of cell selections. Cell_number = Filtered_slice.count(1.0) rm = RoiManager.getInstance() print "Number of selected cells: ", Cell_number print "Total number of selections: ", rm.getCount() Cells = [ Filtered_mean [x : x + Cell_number] for x in xrange (0, len(Filtered_mean), Cell_number) ] Cells_indices = [ index for (index, value) in enumerate(Cells) ] time = [ x for item in timelist for x in repeat(item, Cell_number) ] time = [ time [x : x + Cell_number] for x in xrange (0, len(time), Cell_number) ] Slices = [ Filtered_slice [x : x + Cell_number] for x in xrange (0, len(Filtered_slice), Cell_number) ] # Lists IDD, IDA + IAA if 3ch. if channels == 3: IDD_list = [ Cells [index] for index in Cells_indices [0::int(channels)] ] IDA_list = [ Cells [index] for index in Cells_indices [1::int(channels)] ] IAA_list = [ Cells [index] for index in Cells_indices [2::int(channels)] ] raw_data = {"IDD" : IDD_list, "IDA" : IDA_list, "IAA" : IAA_list, "Cell_num" : Cell_number, "Slices" : Slices, "Time" : time } elif channels == 2: IDD_list = [ Cells [index] for index in Cells_indices [0::int(channels)] ] IDA_list = [ Cells [index] for index in Cells_indices [1::int(channels)] ] raw_data = {"IDD": IDD_list, "IDA" : IDA_list, "Cell_num" : Cell_number, "Slices" : Slices, "Time" : time } return raw_data
def setMeasurementInt(i) : """sets the measurements setting to the int value i, made as a hack to translate an number to its corresponding checkboxes""" a = Analyzer() a.setMeasurements(i)
def getMeasurementInt() : """returns the int value of the measurements setting, made as a hack to translate a set of checkboxes to its corresponding number""" a = Analyzer() i = a.getMeasurements() return i
def run(): '''This is the main function run when the plugin is called.''' #print dir(IJ) ip = IJ.getProcessor() imp = IJ.getImage() # get the current Image, which is an ImagePlus object #print "imp=", type(imp), imp #print dir(imp) roi = imp.getRoi() # get the drawn ROI #print "roi=", roi, roi.getClass() # check ROI type if roi == None: gd = GenericDialog("Draw Measurement - Line") gd.addMessage("Please draw a straight-line first!") gd.showDialog() return #raise Exception( "Please draw a line ROI first!" ) if roi.getTypeAsString() != "Straight Line": gd = GenericDialog("Draw Measurement - Line") gd.addMessage("Please draw a straight-line first!") gd.showDialog() return #raise Exception( "Not a Line ROI! (type="+roi.getTypeAsString()+")" ) # Add auto calibration from text file if sets.autoupdatecal: newcal = imp.getCalibration().copy( ) # make a copy of current calibration object if MC_DEBUG: print("Assume calibration is a custom function.") # call the class' `classObj.cal( ImagePlusObject )` function to get the scale value: try: calObject = sets.autoupdatecal_name calName = calObject.name newPixelPerUnit = calObject.cal(imp) except AttributeError: raise ValueError( 'This calibration Name value is invalid, please check your Settings.py file!/n/tFor Calibration Number %i, got: `' % (CalIdx) + str(cal.names[CalIdx]) + '`. Expected a String or a Class instance with ".cal()" method, but got type ' + str(type(cal.names[CalIdx])) + ' with no ".cal()" method.') #end try newUnit = calObject.unit newAspect = calObject.aspect_ratio newPixelWidth = 1. / newPixelPerUnit newPixelHeight = newPixelWidth * newAspect # the following translated from "Microscope_Scale.java": newcal.setUnit(newUnit) newcal.pixelWidth = newPixelWidth newcal.pixelHeight = newPixelHeight imp.setGlobalCalibration(None) imp.setCalibration(newcal) # set the new calibration imp.getWindow().repaint() # refresh the image? # Added - add the measurement to the list... a = Analyzer(imp) a.measure() a.displayResults() # from ij.measure import ResultsTable # rt = ResultsTable.getResultsTable() p1 = [int(roi.x1d), int(roi.y1d)] # point 1 (x,y) p2 = [int(roi.x2d), int(roi.y2d)] # point 2 #print "DrawMeas(): Line Points: p1=", p1, " & p2=", p2 pm = midpoint(p1, p2) # get midpoint coord # set ROI params from settings: ''' Using new method - used ip.drawLine instead of roi.draw, since roi.draw didn't always apply the line thickness. Would be best to use the ROI method, in case other types of ROI's could be annotated. roi.setStrokeWidth( sets.linethickness ) roi.setStrokeColor( jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3])) ) #roi.drawPixels( ip ) # draw along the ROI - only draws outline unfortunately ip.drawRoi(roi) # draw the ROI on the image ''' ip.setLineWidth(int(sets.linethickness)) ip.setColor( jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3]))) #ip.draw(roi) # changed to ip.drawLine() ip.drawLine(int(roi.x1d), int(roi.y1d), int(roi.x2d), int(roi.y2d)) '''Draw text annotation''' unit = imp.getCalibration().getUnit().encode( 'utf8') # get the unit as UTF-8 (for \mu) #print "Draw_Meas(): Unit (raw) = `", unit,"`", type(unit), if unit[0] == u'\xc2': unit = unit[1:] # strip weird char at start of \mu # format of measurement text (eg. 3 decimal points): lenstr = "%0.3f" % roi.getLength() + " %s" % ( unit) # string to print as length print "DrawMeas(): Line length= %s" % lenstr #print "x,y=", p2[0], p2[1] '''determine position of text from line coords, eg "bottom right" or "top left" etc. ''' # y-coord: if p2[1] > p1[1]: posstr = 'bottom' else: posstr = 'top' # x-coord: if p2[0] > p1[0]: posstr += ' right' else: posstr += ' left' drawText(lenstr, p2[0], p2[1], position=posstr) imp.updateAndDraw() #update the image
def defaultActionSequence(self): """ Central function (DO NOT OVERWRITE) called if a button is clicked or shortcut called It trigger the following actions: - getting the current table - checking the GUI state (checkboxes, dropdown...) - running measurements if measure is selected - setting ROI attribute (if roi) - incrementing table counter - adding image directory and name to table - filling columns from GUI state using custom fillTable() - switching to next slice - displaying the annotation GUI to the front, important to catch next keyboard shortcuts """ try: imp = IJ.getImage() # get current image except: # no image: just stop the execution then return # Get current table table = getTable() table.showRowNumbers(True) # Check options, use getCheckboxes(), because the checkbox plugin have other checkboxes checkboxes = self.getCheckboxes() # Initialize Analyzer if self.runMeasure: analyzer = Analyzer(imp, table) analyzer.setMeasurement(Measurements.LABELS, False) # dont add label to table # Check if existing roi manager rm = RoiManager.getInstance() indexes = rm.getSelectedIndexes() if rm else [ ] # Check if roi selected if indexes: # Loop over selected ROI for index in indexes: # set selected features as property of rois roi = rm.getRoi(index) imp.setRoi(roi) # Run measure for the ROI if self.runMeasure: # Automatically increment counter analyzer.measure() # as selected in Set Measurements else: table.incrementCounter( ) # Automatically done if runMeasure #table.addValue("Index", table.getCounter() ) for key, value in getImageDirAndName(imp).iteritems(): table.addValue(key, value) # Add selected items (implementation-specific) self.fillTable(table) # Read comment stringField = self.getStringFields()[0] table.addValue("Comment", stringField.text) # Add roi name to the table + set its property table.addValue("Roi", roi.getName()) # Add roi name to table setRoiProperties(roi, table) # No roi selected in the Manager else: if self.runMeasure: # also automatically increment counter analyzer.measure() # as selected in Set Measurements else: table.incrementCounter() # Automatically done if runMeasure #table.addValue("Index", table.getCounter() ) for key, value in getImageDirAndName(imp).iteritems(): table.addValue(key, value) # Add selected items (implementation-specific) self.fillTable(table) # Read comment stringField = self.getStringFields()[0] table.addValue("Comment", stringField.text) # Check if an active Roi, not yet present in Manager roi = imp.getRoi() if roi is not None: roi.setPosition(imp) rm = getRoiManager() rm.addRoi(roi) # get back the roi from the manager to set properties roiBis = rm.getRoi(rm.getCount() - 1) roiName = roiBis.getName() table.addValue("Roi", roiName) # Add roi name to table setRoiProperties(roiBis, table) title = table.getTitle() if table.getTitle( ) else "Annotations" # getTitle is None for newly generated table table.show(title) # Update table #table.updateResults() # only for result table but then addValue does not work ! # Go to next slice doNext = checkboxes[-1].getState() if doNext: if self.browseMode == "stack": nextSlice(imp, self.getSelectedDimension()) elif self.browseMode == "directory": NextImageOpener().run("forward") # Bring back the focus to the button window (otherwise the table is in the front) if not IJ.getFullVersion().startswith("1.52p"): WindowManager.toFront(self) # prevent some ImageJ bug with 1.52p