def measureTumor(original, locations):
	'''Returns the area from the original image with the 
	highest kurtosis which generally corresponds to the most
	in focus image. Also saves an image corresponding to a mask
	of the measurement.'''
	# Prevent ROI manager from appearing
	roiM = RoiManager(True)
	ParticleAnalyzer.setRoiManager(roiM)
	# Locate particles above a minimum size and with a desired circularity
	IJ.run(locations, "Analyze Particles...", "size=" + str(minimumCancerArea) +"-" + str(maxCancerArea) +" circularity=" + str(circularityCutoff) + "-1.00 show=Nothing exclude add stack");
	# Choose ROI with the highest kurtosis
	maxKurtosis = None
	area = None
	selectedROI = None
	for roi in roiM.getRoisAsArray():
		original.setRoi(roi)
		stats = original.getStatistics(Measurements.KURTOSIS, Measurements.AREA)
		currentKurtosis = stats.kurtosis
		if currentKurtosis > maxKurtosis:
			maxKurtosis = stats.kurtosis
			area = stats.area
			selectedROI = roi
	original.killRoi() # Remove the remaining ROI
	roiM.runCommand("Reset")
	return (area, selectedROI)
Exemplo n.º 2
0
    def done(self):
        try:
            self.get()  #raise exception if abnormal completion
            awtToolkit.getDefaultToolkit().beep()

            RM = RoiManager()
            rm = RM.getRoiManager()
            self.super__setProgress(100) #
            rm.runCommand(self.imp,"Show All without labels")

            ### We save a temporary RoiSet
            temp_roi_path = gvars['tempFile']
            rm.runCommand("Save", temp_roi_path)
            print "Temp ROIs Saved"

            # We change visibility from frame2 to frame3 once the labelToRoi finishes loading rois
            frame3.setVisible(True)
            frame2.setVisible(False)

            # Enable frame3 buttons in GUI after loading
            f2_btn_original.setEnabled( 1 )
            f2_btn_label.setEnabled( 1 )
            f2_btn_prev.setEnabled( 1 )
            f2_btn_next.setEnabled( 1 )

        except ExecutionException, e:
            raise SystemExit, e.getCause()
Exemplo n.º 3
0
def run():
    global maxDist, minPts

    ip = IJ.getImage()
    roi = ip.getRoi()
    points = roi.getContainedPoints()
    pointList = Arrays.asList(points)
    dplist = []
    for p in pointList:
        array = []
        array.append(p.x)
        array.append(p.y)
        jArray = jarray.array(array, 'd')
        dp = DoublePoint(jArray)
        dplist.append(dp)

    clusterer = DBSCANClusterer(maxDist, minPts)
    clusters = clusterer.cluster(dplist)
    RoiManager()
    roiManager = RoiManager.getRoiManager()
    for c in clusters:
        xCoordinates = []
        yCoordinates = []
        for dp in c.getPoints():
            p = dp.getPoint()
            xCoordinates.append(p[0])
            yCoordinates.append(p[1])
        roi = PointRoi(xCoordinates, yCoordinates)
        roiManager.addRoi(roi)
Exemplo n.º 4
0
		def resetpressed(event):
			self.__ranges.clear()
			self.__image=IJ.getImage()
			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.runCommand("reset")
			self.__image.killRoi()
			IJ.setAutoThreshold(self.__image, "MaxEntropy")
			rt=ResultsTable()
			pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00)
			pa.analyze(self.__image)
			self.__roisArray=[]
			self.__roisArray=rm.getRoisAsArray()
			#rm.runCommand("Show All")
			#rm.runCommand("Select All")
			#rm.runCommand("Set Color", "blue")
			
			IJ.resetThreshold(self.__image)
			
			keys=self.__slidersDict.keys()
			for k in keys:
				if k.endswith("min"): 
					self.__slidersDict[k].setValue(0)
					self.__slidersDict[k].repaint()
				else:
					self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum())
					self.__slidersDict[k].repaint()
def get_roi_manager(new=False):
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    if new:
        rm.runCommand("Reset")
    return rm
Exemplo n.º 6
0
def get_roi_manager(new=False):
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    if new:
        rm.runCommand("Reset")
    return rm
def keep_largest_blob(imp):
    """remove all blobs other than the largest by area"""
    rt = ResultsTable()
    mxsz = imp.width * imp.height
    roim = RoiManager(False)
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                          ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt,
                          0, mxsz)
    pa.setRoiManager(roim)

    for idx in range(1, imp.getImageStackSize() + 1):
        roim.reset()
        rt.reset()
        imp.setPosition(idx)
        pa.analyze(imp)
        rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist()
        mx_ind = rt_areas.index(max(rt_areas))
        indices_to_remove = [
            a for a in range(0, len(rt_areas)) if a != mx_ind
        ]
        indices_to_remove.reverse()
        for rem_idx in indices_to_remove:
            roim.select(imp, rem_idx)
            IJ.run(imp, "Set...", "value=0 slice")
    imp.killRoi()
    roim.reset()
    roim.close()
Exemplo n.º 8
0
	def __init__(self): 
		swing.JFrame.__init__(self, title="Stack Cells")
		self.__impD = IJ.getImage()
		self.setDefaultCloseOperation(swing.JFrame.DISPOSE_ON_CLOSE)
		self.__n=0
		self.__widthl = "11"
		self.__iplist = []
		self.__init = False
		self.__initDIA = False
		self.__initFLUO = False
		self.__skip = False
		self.__avg = True
		self.__mosa = True
		self.__maxfinder = True
		self.__appmedian = True
		self.__fire = True
		self.__align = True
		self.__alignC = False
		self.__enlarge = True
		self.__measures = True
		self.__sens = []
		self.__listrois = []
		self.__cellsrois = []
		self.__Cutoff = 0
		self.__labels = []
		self.__maxraf = 100.0
		self.__minraf = 0.0
		self.__conEllipses = False

		self.__dictCells = {}
		
		self.__rm = RoiManager.getInstance()
		if (self.__rm==None): self.__rm = RoiManager()
		self.run()
Exemplo n.º 9
0
def f2_clic_next(event):
   if 'path_label_image' not in gvars:
      JOptionPane.showMessageDialog(None, "You have to choose at least a label image")

   elif 'path_original_image' in gvars:
      imp = IJ.openImage(gvars['path_original_image']) # IF there isn't an original image, we'll work only and display the results on the label image

   else:
      gvars['path_original_image'] = gvars['path_label_image']
      imp = IJ.openImage(gvars['path_label_image']) # If there is not an original image and only working with the lable, then show the results of the label

   if 'path_original_image' in gvars and 'path_label_image' in gvars:
      RM = RoiManager()        # we create an instance of the RoiManager class
      rm = RM.getRoiManager()

      gvars["workingImage"] = imp
      imp.show()
      IJ.run(imp, "Enhance Contrast", "saturated=0.35");

      imp2 = IJ.openImage(gvars['path_label_image'])
      task = LabelToRoi_Task(imp2) # Executes the LabelToRoi function defined on top of this script. It is wrapped into a SwingWorker in order for the windows not to freeze
      task.addPropertyChangeListener(update_progress) # To update the progress bar
      task.execute()

      rm.runCommand(imp,"Show All without labels")

      f3_txt1.setText("0")
Exemplo n.º 10
0
def keep_blobs_bigger_than(imp, min_size_pix=100):
    """remove all blobs other than the largest by area"""
    imp.killRoi()
    rt = ResultsTable()
    if "Size_filtered_" in imp.getTitle():
        title_addition = ""
    else:
        title_addition = "Size_filtered_"
    out_imp = IJ.createImage("{}{}".format(title_addition, imp.getTitle()),
                             imp.getWidth(), imp.getHeight(), 1, 8)
    out_imp.show()
    IJ.run(out_imp, "Select All", "")
    IJ.run(out_imp, "Set...", "value=0 slice")
    mxsz = imp.width * imp.height
    roim = RoiManager()
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                          ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt,
                          min_size_pix, mxsz)
    pa.setRoiManager(roim)
    roim.reset()
    rt.reset()
    pa.analyze(imp)
    rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist()
    #	print("Number of cells identified: {}".format(len(rt_areas)));
    for idx in range(len(rt_areas)):
        roim.select(out_imp, idx)
        IJ.run(out_imp, "Set...", "value=255 slice")
    mx_ind = rt_areas.index(max(rt_areas))
    roim.reset()
    roim.close()
    imp.changes = False
    imp.close()
    return out_imp
Exemplo n.º 11
0
def getRoiManager():
    """
	Return existing RoiManager or create a new instance if no existing one.
	Always display the RoiManager
	"""
    rm = RoiManager.getInstance()
    if not rm: rm = RoiManager()  # create a new instance
    return rm
Exemplo n.º 12
0
def colorizeTrees(tree, children):
	RoiManager()
	roiManager = RoiManager.getRoiManager()
	colors = {0 : "red", 1 : "green", 2 : "blue", 3 : "yellow", 4 : "magenta", 5 : "cyan"}
	for root in tree.keys():
		roiManager.select(root);
		currentColor = root % len(colors)
		roiManager.runCommand("Set Color", colors[currentColor])
Exemplo n.º 13
0
	def __add(self, event): 
		if ( not self.__init) : 
			IJ.showMessage("", "please start a new stack")
			return
		if ( not self.__initDIA) :
			IJ.showMessage("", "please select an image for DIA")
			return

		if ( not self.__initFLUO) :
			IJ.showMessage("", "please select an image for FLUO")
			return
		
		self.__widthl = self.__display2.getText()
		roi = self.__impD.getRoi()
		
		if roi == None : 
			IJ.showMessage("", "No selection")
			return

		if roi.getType() in [6,7] : 		
			nslice = self.__impD.getCurrentSlice()
			self.__impF.setSlice(nslice)
			self.__impF.setRoi(roi)
		elif roi.getType() in [2,4] :
			nslice = self.__impD.getCurrentSlice()
			self.__impF.setSlice(nslice)
			m=Morph(self.__impF, roi)
			m.setMidParams(10, 2)
			roi=m.MidAxis
			if roi == None :
				self.__display.text = "roi fail"
				if not self.__skip : IJ.showMessage("", "failed roi, please draw it as polyline")
				return				

		#if roi.getType() != 6 : self.__impF.setRoi(roi)
		else : 
			IJ.showMessage("", "This selection is not yet allowed")
			return

		self.__impF.setRoi(roi)
		
		straightener = Straightener()
		new_ip = straightener.straighten(self.__impF, roi, int(self.__widthl))
		
		self.__iplist.append(new_ip)
		self.__labels.append(self.__isF.getShortSliceLabel(nslice))
		
		self.__display.text = self.__name + " cell " + str(len(self.__iplist)) +" width="+str(new_ip.getWidth())+ " height="+ str(new_ip.getHeight())
		roi.setPosition(self.__impD.getCurrentSlice())	

		self.__rm = RoiManager.getInstance()
		if (self.__rm==None): self.__rm = RoiManager()
		
		self.__rm.add(self.__impD, roi, len(self.__iplist))
		self.__cellsrois.append((roi, self.__impD.getCurrentSlice()))
		#self.__rm.runCommand("Show All")

		IJ.selectWindow(self.__impD.getTitle()) 
Exemplo n.º 14
0
def get_clean_RoiManager(show=False):
	'''
	Returns a clean instance of RoiManager.
	'''
	rm = RoiManager.getInstance()
	if not rm:
		rm = RoiManager(show)
	rm.reset()
	return rm
Exemplo n.º 15
0
def f3_clic_saveTable(event):
   print "Click Save Table"
   RM = RoiManager()        # we create an instance of the RoiManager class
   rm = RM.getRoiManager()
   imp = gvars["workingImage"]
   table_message = []
   is_scaled = imp.getCalibration().scaled()
   if not is_scaled:
      JOptionPane.showMessageDialog(None, "Warning: your image is not spatially calibrated. \nTo calibrate, go to Analyze > Set Scale...")

   nChannels = imp.getNChannels()

   print "Total channels:"
   print nChannels
   for current_channel in range(1,nChannels+1):
      print "Current channel:"
      print current_channel

      imp.setSlice(current_channel)
      current_slice = str(imp.getCurrentSlice()) #Get current slice for saving into filename
      print "Current slice:"
      print current_slice

      is_scaled = imp.getCalibration().scaled()
      if is_scaled:
          spatial_cal = "True"
      else:
          spatial_cal = "False"

      IJ.run("Clear Results", "")
      rm.runCommand(imp,"Select All");
      rm.runCommand(imp,"Measure")

      table = ResultsTable.getResultsTable().clone()
      IJ.selectWindow("Results")
      IJ.run("Close")

      filename = os.path.split(gvars["path_original_image"])[1]
      print filename

      pixels = gvars['eroded_pixels'] #To save number of eroded pixels in table and table name

      for i in range(0, table.size()):
         table.setValue('File', i, str(filename))
         table.setValue('Channel', i, current_channel)
         table.setValue('Pixels_eroded', i, str(pixels))
         table.setValue('Spatial_calibration', i, spatial_cal)

      table.show("Tabla actualizada")


      path_to_table = str(gvars['path_original_image'].replace(".tif", "") + "_Erosion_" +str(pixels)+ "px_Channel_" + str(current_channel) + ".csv")
      IJ.saveAs("Results", path_to_table)
      table_message.append("Table saved to %s" % path_to_table)

   JOptionPane.showMessageDialog(None, "\n".join(table_message))
Exemplo n.º 16
0
def particleRemover(image, minArea):
	'''Send in a thresholded image, remove the small spots'''
	numSlices = image.getImageStackSize()
	particleRoiM = RoiManager(True)
	ParticleAnalyzer.setRoiManager(particleRoiM)
	IJ.run(image, "Analyze Particles...", "size=0-" + str(minArea) + " circularity=0.00-1.00 include show=Nothing add stack");
	# Set the fill color to black before filling
	IJ.setForegroundColor(0, 0, 0);
	particleRoiM.runCommand("Fill");
	particleRoiM.runCommand("Reset");
Exemplo n.º 17
0
def run():

    # ensure no other windows are open and clear resultstable
    IJ.run("Close All")
    IJ.run("Clear Results", "")
    #Ask user for file to be converted
    srcDir = IJ.getFilePath("Select file to analyse")
    if not srcDir:
        return

    #open file
    IJ.open(srcDir)
    dstDir = os.path.dirname(srcDir)
    print("dstDir = " + dstDir)
    #open ROI manager, save ROI names as labels in measurements
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    rm.runCommand("UseNames", "true")

    # set parameters to be measured
    IJ.run("Set Measurements...",
           "area mean integrated limit display redirect=None decimal=3")

    FOVlist = WindowManager.getIDList()
    chnls = IJ.getString(
        "Please enter which channels you would like to analyse. Example: 123 analyses channels 1, 2 and 3",
        '123')

    for FOV in FOVlist:
        imp = WindowManager.getImage(FOV)
        IJ.run(imp, "Arrange Channels...", "new=" + chnls)
        imp.close()
        imp2 = WindowManager.getCurrentImage()

        imageTitle = WindowManager.getImage(FOV).getTitle()
        newDir = imageTitle + ' ROIs'

        dirPath = os.path.join(dstDir, newDir)

        if not os.path.exists(dirPath):
            try:
                os.makedirs(dirPath)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
        # clear ROI list before analysis
        rm.runCommand(imp2, "Deselect")
        rm.runCommand(imp2, "Delete")

        TMdata, nFrames = runTrackMate(imp2)
        if TMdata:
            iterateCoords(TMdata, nFrames, dirPath, imp2)
        imp2.changes = 0
        imp2.close()
    #relabel()
    resultsDir = os.path.splitext(srcDir)[0] + ".csv"
    #while os.path.exists(resultsDir):
    #resultsDir = resultsDir+"_1"+".csv"
    IJ.saveAs("Results", resultsDir)
Exemplo n.º 18
0
    def doInBackground(self):
        imp = self.imp
        print "started"

        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
        print st

        # Disable frame3 buttons in GUI while loading ROIs
        f2_btn_original.setEnabled( 0 )
        f2_btn_label.setEnabled( 0 )
        f2_btn_prev.setEnabled( 0 )
        f2_btn_next.setEnabled( 0 )


        RM = RoiManager()        # we create an instance of the RoiManager class
        rm = RM.getRoiManager()  # "activate" the RoiManager otherwise it can behave strangely
        rm.reset()
        rm.runCommand(imp,"Show All without labels") # we make sure we see the ROIs as they are loading


        imp2 = imp.duplicate()
        ip = imp2.getProcessor()
        width = imp2.getWidth()
        height = imp2.getHeight() - 1

        max_label = int(imp2.getStatistics().max)
        max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros)
        IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed

        for j in range(height):
           for i in range(width):
              current_pixel_value = ip.getValue(i,j)
              if current_pixel_value > 0:
                 IJ.doWand(imp2, i, j, 0.0, "Legacy smooth");

                 # We add this ROI to the ROI manager
                 roi = imp2.getRoi()
                 roi.setName(str(int(current_pixel_value)).zfill(max_digits))
                 rm.addRoi(roi)

                 ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", ....

                 # Update ProgressBar
                 progress = int((current_pixel_value / max_label) * 100)
                 self.super__setProgress(progress)

        rm.runCommand(imp,"Sort") # Sort the ROIs in the ROI manager
        rm.runCommand(imp,"Show All without labels")

        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
        print st

        print "Finished"
Exemplo n.º 19
0
def get_clean_RoiManager(show=False):
    '''
	Returns a clean instance of RoiManager.
	'''
    from ij.plugin.frame import RoiManager

    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager(show)
    rm.reset()
    return rm
def drawSpots(spotsByScale):
	RoiManager()
	roiManager = RoiManager.getRoiManager()
	colors = {0 : "red", 1 : "green", 2 : "blue", 3 : "yellow", 4 : "magenta", 5 : "cyan", 6 : "orange", 7 : "black", 8 : "white"}
	print("len-col", len(colors))
	for s in range(1, len(spotsByScale)+1):
		spots = spotsByScale[s]
		for spot in spots:
			roiManager.select(spot['id']);
			currentColor = spot['object'] % len(colors)
			print(spot['id'], spot['object'], currentColor)
			roiManager.runCommand("Set Color", colors[currentColor])
Exemplo n.º 21
0
def apply_roi_arr(func):
    rm = RoiManager()
    rm = rm.getInstance()
    roi_arr = rm.getRoisAsArray()  # => list

    result_list = []
    for roi in roi_arr:
        result = func(roi)
        if result is not None:
            result_list.append(result)

    return result_list
def mergeRois(components):
    RoiManager()
    roiManager = RoiManager.getRoiManager()
    toBeDeleted = []
    for component in components:
        if len(component) > 1:
            roiManager.setSelectedIndexes(component)
            roiManager.runCommand("Combine")
            roiManager.runCommand("Update")
            toBeDeleted = toBeDeleted + component[1:]
    if len(toBeDeleted) > 0:
        roiManager.setSelectedIndexes(toBeDeleted)
        roiManager.runCommand("Delete")
def get_roi_manager(new=False):
    """
	flexible ROI mgr handling, copied from Particles_From_Mask.py template in Fiji
	if new = True, a new blank mgr is returned
	if new = False (default) and the ROI manager is open, returns that mgr.
	if new = False and the ROI manager is NOT open, creates a new one without throwing an error
	"""
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    if new:
        rm.runCommand("Reset")
    return rm
def measure_rm(img_path, roi_path):
    imp = IJ.openImage(img_path)
    img_dir = imp.getOriginalFileInfo().directory
    img_file = imp.getOriginalFileInfo().fileName
    ip = imp.getProcessor()
    cal = Calibration(imp)

    rm = RoiManager()
    rm = RoiManager.getInstance()

    rm.runCommand("Open", roi_path)
    roi_array = rm.getRoisAsArray()

    moptions = Measurements.MEAN | Measurements.AREA

    for roi in roi_array:

        roi_name = roi.getName()
        ip.setRoi(roi)
        stat = ImageStatistics.getStatistics(ip, moptions, cal)

        IJ.log(img_dir + "\t" + img_file + "\t" + roi_name + "\t" +
               str(stat.pixelCount) + "\t" +
               str(stat.pixelCount * stat.umean) + "\t" + str(stat.umean))
    rm.runCommand("delete")
Exemplo n.º 25
0
    def saveCroppedROIs(self, event):
        """ Duplicates cropped ROIs and saves """
        # Create export dir, if not already present
        current_export_dir = self.createExportDir("Cropped_ROI")

        for Image in self.Images.values():  # for all Image instances
            # save image
            cropped_copy = Image.imp.crop()  # returns cropped image as an imp
            img_filename = os.path.join(current_export_dir, Image.title)
            if os.path.splitext(img_filename)[1] != ".tif":
                os.path.join(img_filename, ".tif")
            FileSaver(cropped_copy).saveAsTiff(img_filename)

            # save roi
            roi_filename = os.path.splitext(img_filename)[0] + "_roi.roi"
            roi = Image.imp.getRoi()
            if roi != None:
                rm = RM.getInstance()
                if rm == None:
                    rm = RM()
                rm.addRoi(roi)
                rm.runCommand("Save", roi_filename)  # which one does it save
                rm.runCommand("Delete")
            IJ.log("Cropped ROI saved: " +
                   os.path.join(current_export_dir, Image.title))
def cell_processor(imp_particles, imp_measure, folder, impname, channel_name):

    # Get ROI manager instance, save to zip
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    rm.reset()

    imp_particles.show()

    # Wait for user to add ROIs to manager
    Prefs.multiPointMode = True
    pause = WaitForUserDialog(
        "Select ROIs of interest and add to manager \n \nPress OK to continue")
    pause.show()

    # get the ROI manager and save
    rm = RoiManager.getInstance()
    rm.runCommand("save selected",
                  os.path.join(folder, impname + "_cells_ROIs.zip"))

    # select image to measure and show
    imp_measure.show()
    pixel_collector(rm, imp_measure, channel_name, impname, folder)

    return rm
Exemplo n.º 27
0
def createROI(xy_coord, diameter):
    imp = WindowManager.getCurrentImage()
    pixelWidth = imp.getCalibration().pixelWidth
    pixelHeight = imp.getCalibration().pixelHeight
    x_diameter = diameter / pixelWidth
    y_diameter = diameter / pixelHeight
    x_coord = xy_coord[0] / pixelWidth - (0.5 * x_diameter)
    y_coord = xy_coord[1] / pixelHeight - (0.5 * y_diameter)

    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()

    roi = OvalRoi(x_coord, y_coord, x_diameter, y_diameter)
    rm.addRoi(roi)
Exemplo n.º 28
0
def save_qcd_edges2(edges, output_folder, filename="user_defined_edges.zip"):
    """save edges as rois to a *.zip file"""
    roim = RoiManager(False)
    for edge in edges:
        if edge is not None:
            roim.addRoi(edge)
    roim.runCommand("Save", os.path.join(output_folder, filename))
    roim.close()
Exemplo n.º 29
0
def save_roi_set(imp=IJ.getImage()):
    img_dir, name = get_file_info()
    roi_dir = make_roi_dir(img_dir, name)
    roi_path = make_roi_path(roi_dir, name)
    rm = RoiManager().getInstance()
    rm.deselect()
    rm.runCommand("Save", roi_path)
    rm.runCommand("delete")
Exemplo n.º 30
0
def f3_clic_SaveROIs(event):
   RM = RoiManager()        # we create an instance of the RoiManager class
   rm = RM.getRoiManager()
   pixels = gvars['eroded_pixels']
   path_to_updated_ROIs = str(gvars['path_original_image'].replace(".tif", "") + "_Erosion_" +str(pixels)+ "px_" + "RoiSet.zip")
   rm.runCommand("Save", path_to_updated_ROIs)
   print("ROIs saved")
   print pixels

   #Save Outline Images
   imp = gvars["workingImage"]
   path_to_simple_outline = str(gvars['path_original_image'].replace(".tif", "") + "_Erosion_" +str(pixels)+ "px_" + "Outlines.jpg")
   outlines_image = imp.flatten()
   IJ.saveAs(outlines_image, "JPG", path_to_simple_outline)

   JOptionPane.showMessageDialog(None, "ROIs saved to:\n%s\nOutline image saved to:\n%s" % (path_to_updated_ROIs, path_to_simple_outline))
Exemplo n.º 31
0
def trackEnds(imageID, maskID):
    index = RoiManager.getInstance2().getSelectedIndex()
    inputIMP = WindowManager.getImage(imageID)
    maskIMP = WindowManager.getImage(maskID)
    points1 = inputIMP.getOverlay().get(0).getContainedPoints()[index]
    points2 = inputIMP.getOverlay().get(1).getContainedPoints()[index]
    roi = maskIMP.getOverlay().get(index)
    outerBounds = roi.getBounds()
    impMT, innerBounds = duplicateMaskInRoi(maskIMP, roi, True)
    centroid = impMT.getOverlay().get(0).getContourCentroid()
    nr, endPoint1, endPoint2 = findEndPointsInSkeleton(impMT)
    track1 = trackEnd(impMT, endPoint1, centroid);
    track2 = trackEnd(impMT, endPoint2, centroid);
    impMT.changes=False
    impMT.close()
    newTrack1 = []
    for point in track1:
        newTrack1.append((point.x + outerBounds.x + innerBounds.x - 1,
                         point.y + outerBounds.y + innerBounds.y - 1))
    newTrack2 = []
    for point in track2:
        newTrack2.append((point.x + outerBounds.x + innerBounds.x - 1,
                          point.y + outerBounds.y + innerBounds.y - 1))
    track1X = [point[0] for point in newTrack1]
    track1Y = [point[1] for point in newTrack1]
    roiTrack1 = PolygonRoi(track1X, track1Y, Roi.POLYLINE)
    inputIMP.getOverlay().add(roiTrack1)
    track2X = [point[0] for point in newTrack2]
    track2Y = [point[1] for point in newTrack2]
    roiTrack2 = PolygonRoi(track2X, track2Y, Roi.POLYLINE)
    inputIMP.getOverlay().add(roiTrack2)
    inputIMP.repaintWindow()            
Exemplo n.º 32
0
    def create_nucs(self) :
        """ """
        for cell in self.cells() :
            cell._nucs = []

        rm = RoiManager.getRoiManager()
        rm.reset()

        IJ.run(self.nuc_bin(), "Invert", "")


        rt = ResultsTable.getResultsTable()
        rt.reset()
        IJ.run(self.nuc_bin(), "Analyze Particles...", "add")

        rois = rm.getRoisAsArray()
        IJ.run(self.nuc_bin(),"Remove Overlay", "");



        problem_nucs = []
        for roi in rois :
            nuc_cent = futils.roi_cent(roi, integer=True)

            found_cell = False
            for cell in self.cells() :
                if cell.roi().contains(*nuc_cent) :
                    cell.add_nuc(roi)
                    found_cell = True
                    break

            if not found_cell :
                self.exper.log('Nuc not in any cell for hemisegment {}'.format(self.name))
                problem_nucs.append(roi)
        return problem_nucs
Exemplo n.º 33
0
def make_nucs(hseg):
    """given an hseg, assumed to have a nuc_bin_imp, creates the nuc"""
    rm = RoiManager.getRoiManager()
    rm.reset()

    if UPDATE1:
        IJ.run(hseg.nuc_bin_imp, "Invert", "")

    rt = ResultsTable.getResultsTable()
    rt.reset()
    IJ.run(hseg.nuc_bin_imp, "Analyze Particles...", "add")

    rois = rm.getRoisAsArray()
    problem_nucs = []
    for roi in rois:
        nuc_cent = roi_cent(roi, integer=True)

        found_cell = False
        for cell in hseg.cells.values():
            if cell.roi.contains(*nuc_cent):
                cell.add_nuc(roi)
                found_cell = True
                break

        if not found_cell:
            IJ.log('Nuc not in any cell for hemisegment {}'.format(hseg.name))
            problem_nucs.append(roi)

    return problem_nucs
Exemplo n.º 34
0
def setup() :
	# set setting to save column headers
	IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv use_file save_column");
	force_close_all()
	rm = RoiManager.getRoiManager()
	rm.reset()
	rm.show()
Exemplo n.º 35
0
def main():
    from ij import IJ
    from ij.plugin.frame import RoiManager

    istring = 0
    area_last = 0
    jj = 0

    roim = RoiManager.getInstance()
    istart = roim.getSelectedIndex()
    #istart =0

    ctypes = 'o n'.split()
    for ii, i in enumerate(range(istart, roim.getCount())):
        print(ii)
        roi = roim.getRoi(i)
        if (roi is not None):
            ctype = ctypes[i % 2]
            if (ctype == 'o'):
                area_curr = roi.getStatistics().area
                if (area_curr > 4 * area_last):
                    istring += 1
                    jj = 0
                area_last = area_curr
            jj += 1
            name = "{}-{}-{}".format(istring, jj, ctype)
            roi.setName(name)
            roi.setStrokeWidth(1)

            roim.rename(i, name)
            roim.setRoi(roi, i)
def import_multiple_rois(roi_files):
	rois = [f.getPath() for f in roi_files if f.exists() and f.getName().lower().endswith("roi")]
	opener = Opener()
	rm = RoiManager.getRoiManager()
	if not rm.getInstance():
		rm.reset()
	[rm.addRoi(opener.openRoi(r)) for r in rois]
Exemplo n.º 37
0
def anaParticlesWatershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005):
  """anaParticlesWatershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005)
  A wrapper function to do particle analyis from an image after a watershed transformation and draw the detected
  features into the overlay of the original image.
  Inputs:
  imp        - the ImagePlus instance that we will process
  strThrMeth - a string specifying the threshold method
  minPx      - the minimum pixels to detect
  minCirc    - the minimum circularity to detect
  labCol     - the color for labels in the overlay (default white)
  linCol     - the color for line/stroke in the overlay (default green)
  bDebug     - a flag (default False) that, if true, keeps the work image open
  sl         - a time (default 0.005) to sleep when adding ROIs to not overload

  This adds the detected features to the overlay and returns the result table for
  processing for output.
  """
  title = imp.getTitle()
  shortTitle = imp.getShortTitle()
  
  typ = imp.getType()
  imp.setTitle(shortTitle)
  imp.show()
  IJ.run(imp,"Duplicate...", "title=work")
  wrk = IJ.getImage()
  # if this is a 16 bit image, convert to 8 bit prior to threshold
  if typ == ImagePlus.GRAY16:
    IJ.run(wrk, "Enhance Contrast", "saturated=0.35")
    IJ.run(wrk, "8-bit", "")
  IJ.run(wrk, "Threshold", strThrMeth)
  IJ.run(wrk, "Watershed", "")
  wrk.show()
  strMeas = "area mean modal min center perimeter bounding fit shape feret's display redirect=%s decimal=3" % shortTitle
  IJ.run(wrk, "Set Measurements...", strMeas)
  strAna = "size=%d-Infinity circularity=%g-1.00  exclude clear include add" % (minPx, minCirc)
  IJ.run(wrk, "Analyze Particles...", strAna)
  rt = ResultsTable().getResultsTable()
  rm = RoiManager.getInstance()
  ra = rm.getRoisAsArray()
  # Let's draw the particles into the overlay of the original
  i=0
  for r in ra:
    i += 1
    rLab = "%d" % i
    r.setName(rLab)
    imp = addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol)
    # needed to put in sleep here on cruch to let this complete and not overrun buffer
    time.sleep(sl)
  # let's put a PointRoi outside the image to get the overlays all the same color
  r = PointRoi(-10, -10)
  imp = addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol)
  # clear the roi manager and return the results table
  rm.reset()
  rm.close()
  if bDebug == False:
    wrk.changes = False
    wrk.close()
  imp.setTitle(title)
  return rt
def segmentChannel_Weka(image, **kwargs):
	""" SegmentChannel using a Weka Classification"""
	ch = kwargs['channel']
	if ch > len(image): 
		raise Exception('Expecting at least ' + str(ch) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
	imp = image[ch-1].duplicate()
	ws = WekaSegmentation(imp)	# create an instance
	ws.loadClassifier(kwargs['clspath']) # load classifier
	impProb  = ws.applyClassifier(imp, 0, True)
	impMetaProb = extractChannel(impProb,1,1)
	impMetaProb.setTitle("MetaProb")
	# segmentation
	impBW = threshold(impMetaProb, kwargs['probThr'])
	impMetaProb.show()
	IJ.run("Set Measurements...", " mean center shape area redirect=MetaProb decimal=2");
	
	# particle analysis
	IJ.run(impBW, "Analyze Particles...", "size=10-10000 pixel area circularity=0.00-1.00 display exclude clear stack add");
	rt = Analyzer.getResultsTable()
	validParticles = []
	roim = RoiManager.getInstance()
	if roim == None:
		raise Exception('Fiji error segmentNuclei.py: no RoiManager!')
	if roim.getCount() > 0:
		rois = roim.getRoisAsArray()
	else:
		IJ.log("# particles = 0")
		return impMetaProb, impBW, None, None
	X = rt.getColumn(rt.getColumnIndex("XM"))
	Y = rt.getColumn(rt.getColumnIndex("YM"))
	Mean = rt.getColumn(rt.getColumnIndex("Mean"))
	Circ = rt.getColumn(rt.getColumnIndex("Circ."))
	Area = rt.getColumn(rt.getColumnIndex("Area"))
	print "# particles = " + str(len(Mean))
	nValid = 0
	for i in range(len(Mean)):
		valid = (Mean[i]>kwargs['minProb']) and (Circ[i]<kwargs['maxCirc']) # filter particles post detection
		if(valid):
			validParticles.append([i, X[i], Y[i], Mean[i]])
	print validParticles
	IJ.log("# valid particles = %d " % len(validParticles))
	# sort particles according to Mean
	validParticlesSorted = sorted(validParticles, key=itemgetter(3))
	# only keep the three with the largest Mean
	validParticles = validParticlesSorted[-int(kwargs["nrPart"]):]
    #random.shuffle(validParticles)
	IJ.log("# valid particles = %d " % len(validParticles))
	if len(validParticles) == 0:
		validParticles = None
	return impMetaProb, impBW, validParticles, rois
Exemplo n.º 39
0
    def grab(self, dialog_options=None):
        """ Get the image patches using the ROI manager.
        """

        if not dialog_options:
            return

        # get a refence to the ROI manager and check that we have ROIs!
        rm = RoiManager.getRoiManager()
        num_ROIs = rm.getCount()
        if num_ROIs < 1: return None

        if dialog_options['rename']:
            for r in xrange(num_ROIs):
                rm.getRoi(r).setName('{0:s}_{1:s}_{2:d}'.format(self.session_id,dialog_options['label'],r))

        return [ClassifierROI(rm.getRoi(r), path=dialog_options['path']) for r in xrange(num_ROIs)]
Exemplo n.º 40
0
def filter_hough():
	new_image = IJ.getImage()
	# Get the roi manager
	roi_manager = RoiManager.getInstance()
	roi_array = roi_manager.getRoisAsArray()

	for cur_roi in roi_array:
		new_image.setRoi(cur_roi)
		stats = new_image.getStatistics(Measurements.CENTROID)
		x_centroid_list.append(stats.xCentroid)
		y_centroid_list.append(stats.yCentroid)

	# Close the new image
	new_image.killRoi() # Remove the remaining ROI
	roi_manager.runCommand("Reset")
	roi_manager.runCommand("Close")
	new_image.changes = False
	new_image.close()
Exemplo n.º 41
0
	def ShowRoi(self,imp,point, name):
		for indices in self.__gridrectangle.keys() :
			if self.__gridrectangle[indices].contains(point) :
				roitemp=self.__dictCells[name][self.__listcellname[indices[0]-1]].getRoi(indices[1]-1)
		if isinstance(roitemp,Roi) :
			idimages=WindowManager.getIDList()
			for i in range(len(idimages)) :
				if idimages[i]==self.__img.getID() :
					IJ.selectWindow(self.__img.getID())	
			rm = RoiManager.getInstance()
			for i in range(rm.getCount()) :
				if rm.getName(str(i))==roitemp.getName() :
					rm.select(i)
					selectroi=self.__img.getRoi()
					#col=rm.getSelectedRoisAsArray().getStrokeColor()
					selectroi.setStrokeColor(Color.red)
					selectroi.setStrokeWidth(3)
					self.__img.updateAndDraw()
					break
Exemplo n.º 42
0
    def write(self, ROIs=None, dialog_options=None):
        """ Write out the classifier info
        """

        if not dialog_options or not isinstance(ROIs, list):
            return

        # get the data stack
        channels = ['BF', 'GFP', 'RFP']
        channels_to_use = [c for c in channels if dialog_options[c] != 'None']
        print channels_to_use


        for c in channels_to_use:
            for r in ROIs:
                IJ.log("Grabbing patches for ROI: "+ r.name)
                r.window_size = dialog_options['window_size']
                r.save = dialog_options['save']
                r(data=WindowManager.getImage(dialog_options[c]), channel=c)


        if dialog_options['zip']:
            roi_fn = os.path.join(dialog_options['path'], dialog_options['label']+'_'+str(self.session_id)+'_ROIset.zip')
            rm = RoiManager.getRoiManager()
            rm.runCommand('Select All')
            rm.runCommand('Save', roi_fn)

        # old style dictionary comprehension
        ROI_dict = dict((r.name,{'frame':r.index, 'x':r.x, 'y':r.y}) for r in ROIs)
        ROI_dict['opts'] = dialog_options

        # save out a pickled dictionary with all of the details
        if dialog_options['save']:
            pass
            # try:
            #     classifier_file = open(os.path.join(dialog_options['path'],dialog_options['data']+'_classifier.p'), 'wb')
            #     pickle.dump( ROI_dict, classifier_file, -1)
            #     classifier_file.close()
            # except IOError:
            #     IJ.log('Could not pickle classifier info file.')

        print ROI_dict
Exemplo n.º 43
0
	def __displayCells(self, nameimage, methodeleon=False):
		"""
		Displays all the ROIs of the cells with different colors
		
		"""
		# we define a list of colors that will be used.

		colors = []
		ncells= len(self.__dict[nameimage])
		if ncells > 0 :
			step=200/ncells
			if step<1 : step=1
			for i in range(ncells) : 
				r = random.randrange(5,205,step)
				g = random.randrange(10,210,step)
				b = random.randrange(30,230,step)
				#r = int(0+i*step)
				#g = random.randrange(10, 190, 30)
				#b = int(250-i*step)
				
				colors.append(Color(r, g, b))

		else : 	colors=[Color.blue, Color.green, Color.magenta, Color.orange, Color.yellow]
		tempcolors=list(colors)
		# we try to have random and different colors for each cell.
		for cellname in self.__dict[nameimage].keys() :
			if len(tempcolors)>0 : 
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
			else :
				tempcolors=list(colors)
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
		

		self.__SaveCells(nameimage)
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		# if the user wants to save files, .zip for the ROIs are saved.
		#if self.__optionSave == True : 
		#os.mkdir(self.__pathdir+"ROIs/", mode=0777)
		os.makedirs(self.__pathdir+"ROIs/", mode=0777)
		tempimp = IJ.createImage("tempimp", "8-bit Black", self.__dictImages[nameimage].getWidth(), self.__dictImages[nameimage].getHeight(), 1)
		tempimp.show()
		for cellname in self.__dict[nameimage].keys() :
			for numslice in range(self.__dictImages[nameimage].getImageStackSize()) :
				r = self.__dict[nameimage][cellname].getRoi(numslice)
				try : 
					name=r.getName()
				
				except AttributeError : continue

				else :
					s = "%04i" % (numslice+1)
					#name=s+"-"+name.split("-", 1)[1]
					name=s+"-cell"+name.split("cell")[1]
					r.setName(name)
					try :
						rm.addRoi(r)
						rname=rm.getName(rm.getCount()-1)
						#rm.select(self.__dictImages[nameimage], rm.getCount()-1)
						rm.select(tempimp, rm.getCount()-1)
						rm.runCommand("Rename", name)
					except TypeError : continue
					
					
				#if isinstance(self.__dict[nameimage][cellname].getRoi(numslice),Roi) == True :
				#	s = "%04i" % (numslice)
				#	#rm.add(self.__dictImages[nameimage], self.__dict[nameimage][cellname].getRoi(numslice)  ,  numslice)
				#	name=self.__dict[nameimage][cellname].getRoi(numslice).getName()
				#	name=s+name
				#	self.__dict[nameimage][cellname].getRoi(numslice).setName(name)
				#	rm.addRoi(self.__dict[nameimage][cellname].getRoi(numslice))
			rm.runCommand("Save", self.__pathdir+"ROIs/"+cellname+".zip")
			rm.runCommand("reset")
		
		tempimp.close()
 validParticles
	random.shuffle(validParticles)
	if kwargs['command'] != 'nothing':
		autTool.writePositionToRegistry([[part[1], part[2]] for part in validParticles[0:int(kwargs["nrPart"])]])
	IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+kwargs['command']+"] windows=REG_SZ")
	return validParticles

test = 0



if test ==0:
	locDialogParameters('Weka_Metaphase_Detection')
	
if test ==1 :
	IJ.run("Close All", "");
	roim = RoiManager.getInstance()
	if roim == None:
		roim = RoiManager()
	
	roim.runCommand("reset");
	imagePath =	r"C:\Users\toni\Code\AutomatedMicroscopy\IJMacros\WekaPipeline\TestImage_1024.tif"
	imp = IJ.openImage(imagePath)
	imp.show()
	kwargs={'pip':'Default', 'task':1, 'channel':1, 'command':"trigger1", 'clspath':"C:\\Users\\toni\\Code\\AutomatedMicroscopy\\IJMacros\\WekaPipeline\\classifier.model", 'nrPart':3, 
	'Min Intensity':0.8, 'maxCirc': 0.8, 'probThr':0.6}
	
	procs, segs, validParticles, rois =  segmentChannel_Weka([imp], **kwargs)
	executeTask_Weka(validParticles,  **kwargs)
	particle = [part[0] for part in validParticles]
	print particle
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	title =  inputImp.getTitle()
	title=title.replace('UV', 'SD')
	
	print title
	
	#trueColorImp= WindowManager.getImage(title)
	#print type( trueColorImp)
	
	# calculate are of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	print inputRoi
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1

	print x1
	print y1
	print x2
	print y2
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	#duplicate.show()
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	redPlus.show()
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	APlus.show()
	APlus.getProcessor().resetMinAndMax()
	APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	#redMask.show()
	
	labPlus.close()
	
	# threshold the spots from the red channel
	thresholdedred=SpotDetectionGray(red, data, display, ops, False)
	display.createDisplay("thresholdedred", data.create(thresholdedred))
	impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	
	# threshold the spots from the brightness channel
	thresholded=SpotDetectionGray(brightness, data, display, ops, False)
	display.createDisplay("thresholded", data.create(thresholded))
	impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, clone)
	
	# create a hidden roi manager
	roim = RoiManager(True)
	
	# count the particlesimp.getProcessor().setColor(Color.green)
	countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity)
	
	# define a function to determine the percentage of pixels that are foreground in a binary image
	# inputs:
	#    imp: binary image, 0=background, 1=foreground
	#    roi: an roi
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return False
		else: return True

	allList=[]

	for roi in roim.getRoisAsArray():
		allList.append(roi.clone())
	
	# count particles that are red
	redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed)
	# count particles that are red
	blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed)

	print "Total particles: "+str(len(allList))
	print "Filtered particles: "+str(len(redList))

	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList]
	
	# create an overlay and add the rois
	overlay1=Overlay()
		
	inputRoi.setStrokeColor(Color.green)
	overlay1.add(inputRoi)
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList]
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList]
	
	def drawAllRoisOnImage(imp, mainRoi, redList, blueList):
		imp.getProcessor().setColor(Color.green)
		IJ.run(imp, "Line Width...", "line=3");
		imp.getProcessor().draw(inputRoi)
		imp.updateAndDraw()
		IJ.run(imp, "Line Width...", "line=1");
		[CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList]
		[CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList]
		imp.updateAndDraw()
	
	drawAllRoisOnImage(inputImp, inputRoi, redList, blueList)
	#drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList)
	
	# draw overlay
	#inputImp.setOverlay(overlay1)
	#inputImp.updateAndDraw()
	
	statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	print inputRoiArea

	areas=statsdict['Areas']
	poreArea=0
	for area in areas:
		poreArea=poreArea+area

	ATotal=0
	ALevels=statsdict['ALevel']
	for A in ALevels:
		ATotal=ATotal+A

	AAverage=ATotal/len(ALevels)

	BTotal=0
	BLevels=statsdict['BLevel']
	for B in BLevels:
		BTotal=BTotal+B

	BAverage=BTotal/len(BLevels)

	redTotal=0
	redPercentages=statsdict['redPercentage']
	for red in redPercentages:
		redTotal=redTotal+red

	redAverage=redTotal/len(redPercentages)
	pixwidth=inputImp.getCalibration().pixelWidth

	inputRoiArea=inputRoiArea/(pixwidth*pixwidth)
	
	print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):

	# set calibration
	detectionParameters.setCalibration(inputImp);
	
	# calculate area of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	#cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) 
	cropped=ops.image().crop(inputDataset.getImgPlus() , interval) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	# instantiate the duplicator and the substackmaker classes
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()

	croppedPlus.changes=False
	croppedPlus.close()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	#APlus.show()
	APlus.getProcessor().resetMinAndMax()
	#APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	#BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	#BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	
	labPlus.close()

	fast=True
	
	# threshold the spots from the red channel
	if (fast==False):
		thresholdedred=SpotDetectionGray(red, data, display, ops, "triangle")
		impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	else:
		impthresholdedred=SpotDetection2(redPlus)
	
	# threshold the spots from the brightness channel
	if (fast==False):
		thresholded=SpotDetectionGray(brightness, data, display, ops, "triangle")
		impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	else:
		impthresholded=SpotDetection2(brightnessPlus)
		
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	roim=RoiManager(True)
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.porphyrinRedPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.porphyrinRedPercentage): return False
		else: return True


	roiClone=inputRoi.clone()
	roiClone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, roiClone)

	impthresholded.show()
	
	countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \
		detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity)
	
	uvPoreList=[]
	for roi in roim.getRoisAsArray():
		uvPoreList.append(roi.clone())

	
	#allList=uvPoreList+closedPoresList+openPoresList
	
	# count particles that are porphyrins (red)
	porphyrinList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, isRed)
	# count particles that are visible on uv but not porphyrins
	sebumList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, notRed)

	
	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in uvPoreList]
	
	# draw the ROIs on to the image
	inputImp.getProcessor().setColor(Color.green)
	IJ.run(inputImp, "Line Width...", "line=3");
	inputImp.getProcessor().draw(inputRoi)
	IJ.run(inputImp, "Line Width...", "line=1");
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList]	
	inputImp.updateAndDraw()

	# calculate stats for the UV visible particles
	detectionParameters.setCalibration(APlus)
	statsDictUV=CountParticles.calculateParticleStatsUV(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	totalUVPoreArea=0
	for area in statsDictUV['Areas']:
		totalUVPoreArea=totalUVPoreArea+area
	averageUVPoreArea=totalUVPoreArea/len(statsDictUV['Areas'])

	poreDiameter=0
	for diameter in statsDictUV['Diameters']:
		poreDiameter=poreDiameter+diameter
	poreDiameter=poreDiameter/len(statsDictUV['Diameters'])

	redTotal=0
	for red in statsDictUV['redPercentage']:
		redTotal=redTotal+red
	redAverage=redTotal/len(statsDictUV['redPercentage'])

	statslist=[len(porphyrinList), 100*redAverage];
	statsheader=[Messages.Porphyrins,  Messages.PercentageRedPixels]

	print("Roi Area: "+str(inputRoiArea))
	print("Total Pore Area: "+str(totalUVPoreArea))
	print("Average Pore Area: "+str(averageUVPoreArea))
	print str(len(uvPoreList))+" "+str(len(porphyrinList))+" "+str(len(sebumList))+" "+str(100*totalUVPoreArea/inputRoiArea)+" "+str(100*redAverage)
	print "cp min circularity"+str(detectionParameters.closedPoresMinCircularity)+":"+str(detectionParameters.closedPoresMinSize)

	# close the thresholded image
	impthresholded.changes=False
	impthresholded.close()
	
	return uvPoreList, statslist, statsheader
Exemplo n.º 47
0
# @LogService log

# This script exemplifies how to instruct KymographBuilder to
# process all the line ROIs present in the ROI Manager. For more
# details see http://imagej.net/KymographBuilder
import ij.plugin.frame.RoiManager as RM
import sc.fiji.kymographBuilder.KymographFactory as KFactory


def validDataset(dataset):
    """Assess if dataset has suitable dimensions"""
    from net.imagej.axis import Axes
    z = dataset.dimension(dataset.dimensionIndex(Axes.Z))
    t = dataset.dimension(dataset.dimensionIndex(Axes.TIME))
    return z * t > 1


rm = RM.getInstance()
counter = 0
if validDataset(dataset) and rm and rm.getCount():
    for roi in rm.getRoisAsArray():
        if roi.isLine():
            kfactory = KFactory(context, dataset, roi)
            kfactory.build()
            counter += 1
            title = "Kymograph" + str(counter).zfill(3) + "_" + roi.getName()
            ij.ui().show(title, kfactory.getKymograph())
    log.info("MultiKymographBuilder Finished. " + str(counter) + " ROIs processed")
else:
    log.error("Either the ROI Manager is empty or " + dataset.getName() +" has invalid dimensions")
Exemplo n.º 48
0
		#panel0.add(updatebutton)
		#panel0.add(resetbutton)
		#gd0.addPanel(panel0)

		gd0.setResizable(True) 
		
		gd0.showDialog()
		#self.__image.setSlice(self.__firstslice)
		#self.__image.updateAndDraw()
			
				
		if gd0.wasOKed():
			#for key in self.__ranges.keys(): IJ.log("Measure : "+str(self.__ranges[key][0])+" min = "+str(self.__ranges[key][1])+" max = "+str(self.__ranges[key][2]))
			return self.__ranges

	
	includeRois=property(getIncludeRois, doc="rois include in the measures ranges")
		
#----- end class ----------

if __name__ == "__main__":
	rm=RoiManager.getInstance()
	rois=rm.getRoisAsArray()
	img=IJ.getImage()
	r=RangeRois(rois, img)
	r.showSettingsDialog()
	for roi in r.includeRois : print roi.getName()
	
	
	
	
Exemplo n.º 49
0
	def makeCell(cellfile) :

		filetemp = open(cellfile,"r")
		linestemp=filetemp.readlines()
		for line in linestemp :
			params=line.split("=")
			values=params[1].split("\n")
			if params[0] == "NAMECELL" :
				celltemp=Bacteria_Cell(str(values[0]))
			if params[0] == "PATHROIS" :
				pathtemp = str(values[0])
			if params[0] == "NSLICES" : 
				for i in range(int(values[0])) :
					celltemp.getListRoi().append("")
			if params[0] == "SLICEINIT" :
				celltemp.setSlideInit(int(values[0]))
				#for i in range(int(values[0])-2) :
				#	celltemp.setRoi("NOT HERE YET",i)
			if params[0] == "SLICEEND" :
				celltemp.setSlideEnd(int(values[0]))
				#for i in range(int(values[0])) :
				#	celltemp.setRoi("LOST",i)
				
			if params[0] == "COLOR" :
				colorstemp=values[0].split(";")
				celltemp.setColor(Color(int(colorstemp[0]),int(colorstemp[1]),int(colorstemp[2])))

		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")
		rm.runCommand("Open", pathtemp)
		rois=rm.getSelectedRoisAsArray()
		celltemp.setlistRois(rois)
		rm.runCommand("UseNames", "true")
		rm.runCommand("Associate", "true")

		return celltemp
Exemplo n.º 50
0
	def __ImportCells(self, imagesnames) :

		#self.__dictCells[imgName]={}
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		listpaths = []
		listfilescells=[]

		if self.__optionImages :
			IJ.showMessage("Select the folder 'Cells' containing the cells to import")
			selectdir=IJ.getDirectory("image")
			selectdir=IJ.getDirectory("")
			listfilescells.extend(glob.glob(selectdir+os.path.sep+"*"))
			listpaths.append("")

		else : 
			IJ.showMessage("Select the text file containing the list cell paths (listpaths.txt)")
			selectdir=IJ.getDirectory("current")
			frame = Frame("Text file settings ?")
			fd = FileDialog(frame)
			fd.setDirectory(selectdir)
			fd.show()
			selectdir = fd.getDirectory() 
			textfile = fd.getFile()
			fichier = open(selectdir+textfile,"r")
			listpaths=[ glob.glob(f.split("\n")[0]+"Selected-Cells"+os.path.sep+"*") for f in fichier.readlines()]

			#for f in templist : 
			#	listpaths.append(f.split("\n")+"Cells")
				
			listfilescells.append("")

		if listfilescells[0]=="" : importmode = True
		else : importmode = False
		
		for j in range(len(listpaths)) :
			self.__dictCells[imagesnames[j]]={}
			if importmode : listfilescells = listpaths[j]
			pathtemp = []
			for cellfile in listfilescells :
				filetemp = open(cellfile,"r")
				linestemp=filetemp.readlines()
				for line in linestemp :
					params=line.split("=")
					values=params[1].split("\n")
					if params[0] == "NAMECELL" :
						celltemp=Bacteria_Cell(str(values[0]))
						self.__dictCells[imagesnames[j]][values[0]]=celltemp
						self.__dictMeasures[self.__dictCells[imagesnames[j]][values[0]]]={} 


					if params[0] == "PATHROIS" :
						pathtemp.append(str(values[0]))
						
					if params[0] == "NSLICES" : 
						for i in range(int(values[0])) :
							celltemp.getListRoi().append("")
				
					if params[0] == "SLICEINIT" :
						celltemp.setSlideInit(int(values[0]))
						for i in range(int(values[0])-2) :
							celltemp.setRoi("NOT HERE YET",i)
				
					if params[0] == "SLICEEND" :
						celltemp.setSlideEnd(int(values[0]))
						for i in range(int(values[0])) :
							celltemp.setRoi("LOST",i)
				
					if params[0] == "COLOR" :
						colorstemp=values[0].split(";")
						celltemp.setColor(Color(int(colorstemp[0]),int(colorstemp[1]),int(colorstemp[2])))
		
		
			indiceroi=0
			ind=0
			tempimp = WindowManager.getImage(imagesnames[j])
			if tempimp is not None : 
				IJ.selectWindow(imagesnames[j])
				tempimp.show()
			else : 
				if imagesnames[j][-4:]==".tif" : 
					IJ.selectWindow(imagesnames[j][:-4])
					tempimp = IJ.getImage()
				else : 
					IJ.selectWindow(imagesnames[j]+".tif")
					tempimp = IJ.getImage()
					
			rm.runCommand("reset")
			
			for cellname in self.__dictCells[imagesnames[j]].keys() :
				rm.runCommand("Open", pathtemp[ind])
				ind+=1
				nbtemp=self.__dictCells[imagesnames[j]][cellname].getLifeTime()
				for i in range(nbtemp) :
					rm.select(tempimp, indiceroi)
					roi=rm.getSelectedRoisAsArray()[0]
					self.__dictCells[imagesnames[j]][cellname].setRoi(roi,i+self.__dictCells[imagesnames[j]][cellname].getSlideInit()-1)
					indiceroi+=1

			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(tempimp, "Labels...", "color=red font=12 show use")
			if rm.getCount()>0 : IJ.run(tempimp, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")

			roipath = os.path.split(pathtemp[0])[0]+os.path.sep
			rootpath = roipath.rsplit(os.path.sep, 2)[0]+os.path.sep

			self.__listpaths[j] = rootpath
			self.__rootpath=rootpath
def poreDetectionTrueColor(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	detectionParameters.setCalibration(inputImp);
	
	# calculate area of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	cropped=ops.image().crop(inputDataset.getImgPlus(), interval ) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	# instantiate the duplicator and the substackmaker classes
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)

	# separate into RGB and get the blue channel
	IJ.run(duplicate, "RGB Stack", "")
	bluePlus=substackMaker.makeSubstack(duplicate, "3-3")
	blue=ImgPlus(ImageJFunctions.wrapByte(bluePlus))
	bluePlus.setTitle("Blue")
	
	# duplicate and look for bright spots
	thresholdedLight=SpotDetection2(bluePlus)

	# duplicate and look for dark spots
	thresholdedDark=SpotDetection3(bluePlus, True)

	# convert to mask
	Prefs.blackBackground = True
	#IJ.run(thresholdedDark, "Convert to Mask", "")substackMaker

	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(thresholdedLight, clone)
	Utility.clearOutsideRoi(thresholdedDark, clone)
	roimClosedPores = RoiManager(True)
	detectionParameters.setCalibration(thresholdedDark)
	countParticles(thresholdedDark, roimClosedPores, detectionParameters.closedPoresMinSize, detectionParameters.closedPoresMaxSize, \
		detectionParameters.closedPoresMinCircularity, detectionParameters.closedPoresMaxCircularity)

	# count number of open pores
	roimOpenPores = RoiManager(True)
	detectionParameters.setCalibration(thresholdedDark)
	countParticles(thresholdedDark, roimOpenPores, detectionParameters.openPoresMinSize, detectionParameters.openPoresMaxSize, \
		detectionParameters.openPoresMinCircularity, detectionParameters.openPoresMaxCircularity)

	# count number of sebum
	roimSebum = RoiManager(True)
	detectionParameters.setCalibration(thresholdedLight)
	countParticles(thresholdedLight, roimSebum, detectionParameters.sebumMinSize, detectionParameters.sebumMaxSize, \
		detectionParameters.sebumMinCircularity, detectionParameters.sebumMaxCircularity)
	
	# create lists for open and closed pores
	closedPoresList=[]
	for roi in roimClosedPores.getRoisAsArray():
		closedPoresList.append(roi.clone())
	openPoresList=[]
	for roi in roimOpenPores.getRoisAsArray():
		openPoresList.append(roi.clone())

	# create lists for sebum
	sebumsList=[]
	for roi in roimSebum.getRoisAsArray():
		sebumsList.append(roi.clone())

	# a list of all pores
	allList=closedPoresList+openPoresList+sebumsList
	
	# calculate the stats for all pores
	detectionParameters.setCalibration(bluePlus)
	statsDict=CountParticles.calculateParticleStats(bluePlus, allList)

	poresTotalArea=0
	for area in statsDict['Areas']:
		poresTotalArea=poresTotalArea+area
		print area
	poresAverageArea=poresTotalArea/len(statsDict['Areas'])
		

	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList]
	
	# draw the rois on the image
	inputImp.getProcessor().setColor(Color.green)
	IJ.run(inputImp, "Line Width...", "line=3");
	inputImp.getProcessor().draw(inputRoi)
	IJ.run(inputImp, "Line Width...", "line=1");
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.red) for roi in closedPoresList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in openPoresList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumsList]
	
	inputImp.updateAndDraw()
	
	# close images that represent intermediate steps
	croppedPlus.changes=False
	croppedPlus.close()
	bluePlus.changes=False
	bluePlus.close()

	print "Total ROI Area: "+str(inputRoiArea)
	print "Num closed pores: "+str(len(closedPoresList))
	print "Num open pores: "+str(len(openPoresList))
	print "Num sebums: "+str(len(sebumsList))
	
	print "Total particles: "+str(len(allList))+ " total area: "+str(poresTotalArea)
	
	statslist=[inputRoiArea, len(allList), len(closedPoresList), len(openPoresList), len(sebumsList), poresAverageArea, 100*poresTotalArea/inputRoiArea]
	header=[Messages.TotalAreaMask, Messages.TotalDetectedPores, Messages.ClosedPores, Messages.OpenPores, Messages.Sebum, Messages.PoresAverageArea, Messages.PoresFractionalArea]
	
	return header,statslist

	
    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    ok = trackmate.process()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))


    #----------------
    # Display results
    #----------------

    # The feature model, that stores edge and track features.
    fm = model.getFeatureModel()
    rm = RoiManager.getInstance()
    if not rm:
          rm = RoiManager()
    rm.reset()
    nextRoi = 0

    for id in model.getTrackModel().trackIDs(True):

        # Fetch the track feature from the feature model.
        v = fm.getTrackFeature(id, 'TRACK_MEAN_SPEED')
        v1 = fm.getTrackFeature(id, TrackBranchingAnalyzer.NUMBER_SPLITS)

        if (v1>0):
            model.getLogger().log('')
            model.getLogger().log('Track ' + str(id) + ': branching = ' + str(v1))
            track = model.getTrackModel().trackSpots(id)
	def runOnFile(self, afile, show = True, jobnr = None):
		afile = str(afile)
		if afile == '' or afile is None:
			od = OpenDialog("Choose image file", None)
			if od.getFileName() == None:
				return
			afile = os.path.join(od.getDirectory(), od.getFileName())
		if '.log' in afile:
			return
		
		try:
			zk = ZeissKeys()
			msg = Message()
			print "Hi"
			if self.jobs is None:
				IJ.showMessage("You need to first set the parameters")
			
			if all([job['pip']=='None' for job in self.jobs]):
				IJ.showMessage("Nothing to do! At least on job different than None") 
				return 0
			
			#create a copy otherwise self.jobs gets overwritten
			jobs = copy.deepcopy(self.jobs)
			random.seed()
			
			#create a roiManager in case one is missing and reset it
			roim = RoiManager.getInstance()
			if roim == None:
				roim = RoiManager()
			roim.runCommand("reset")
			
			for i, job in enumerate(self.jobs):
				jobl = job #not really necessary
				if jobl['pip'] == 'None':
					continue
				self.JOBS_DICT[jobl['pip']] + jobl['task'] + "_" 
				
				if jobnr is not None:
					if jobnr == i:
						#force opening
						imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']), 1)
					else: 
						continue
				else:
					imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']))
				print imageDef
				jobl['channel'] = int(jobl['channel'])
				
				if imageDef is None:
					continue
				#clean up registry for errors
				IJ.log("Clean up errorMsg registry")
				IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_errormsg+" value=[""] windows=REG_SZ")
				
				[imageC, pixelSize, filepath, filename] = imageDef
				if jobl['channel'] > len(imageC):
					raise IOError('Expecting at least ' + str(jobl['channel']) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
				
				self.rois = [None]*self.nrOfJobs
				self.Segs = [None]*self.nrOfJobs
				self.Procs = [None]*self.nrOfJobs
				#switch color to Cyan for better visibility
				IJ.run(imageC[jobl['channel']-1], "Cyan", "")

				#segment
				self.Procs[i], self.Segs[i], validParticles, self.rois[i] = segmentChannel_Weka(imageC, **jobl)
				if validParticles is None:
					IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ")

				#write values to registry
				try:
					executeTask_Weka(validParticles, **jobl)
				except Exception, err:
					self.exitWithError(str(err))
					return
				
				if self.rois[i] is None:
					imageC[jobl['channel']-1].show()
					self.Segs[i].show()
					self.Procs[i].show()
					continue
				if validParticles is None:
					particle = []
				else:
					particle = [part[0] for part in validParticles]
				imgOut = autTool.createOutputImg(imageC[jobl['channel']-1], self.rois[i], particle)
				
				imgOut.show()	
				self.saveOutputImg(imgOut, filepath, i+1)			
				
			IJ.run("Collect Garbage", "")
Exemplo n.º 54
0
	def showSettingsDialog(self):
		if self.__image.getOverlay() is not None : self.__image.getOverlay().clear()
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		#rm.runCommand("Deselect")
		#for i in range(rm.getCount()) : 
		#	rm.select(i)
		#	rm.runCommand("Set Color", "0000FF", 2)
		
		
		IJ.resetThreshold(self.__image)

		rm.runCommand("Show All")
		
		self.__ranges.clear()
		#areas, means, majors, minors=[],[],[],[]

		#for roi in self.__roisArray:
		#	m=Morph(self.__image, roi)
		#	areas.append(m.Area)
		#	means.append(m.Mean)
		#	majors.append(m.Major)
		#	minors.append(m.Minor)
			
		#maxarea=max(areas)*1000
		#maxint=max(means)*10
		#maxline=max(majors)*100
		#maxminline=max(minors)*100
		#minline=min(minors)
		
		#namemeasures=["Area", "Mean", "Angle", "Major", "Minor", "Solidity", "AR", "Round", "Circ"]
		#maxmeasures=[maxarea, maxint, 180*10, maxline, maxminline, 1*1000, (maxline/minline), 1*1000, 1*1000]
		#set1000=Set(["Solidity", "Round", "Circ"])
		#set10=Set(["Angle"])
		
		def buttonPressed(event):
			temprois=self.getIncludeRois()
			for roi in temprois:
				m=Morph(self.__image, roi)
				IJ.log("----------------------------------")
				IJ.log(roi.getName())
				for r in self.__ranges.values():
					IJ.log(r[0]+" min= "+str(r[1])+" < val="+str(m.__getattribute__(r[0]))+" < max= "+str(r[2]))
			IJ.run(self.__image, "Remove Overlay", "")
			o=Overlay()
			for roi in temprois:
				o.addElement(roi)
			self.__image.killRoi()
			self.__image.setOverlay(o)
			self.__image.updateAndDraw()

		def updatepressed(event):
			self.__image=IJ.getImage()
			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.runCommand("reset")
			self.__image.killRoi()
			IJ.run("Threshold...")
			IJ.setAutoThreshold(self.__image, "MaxEntropy")
			
			rt=ResultsTable()
			pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00)
			pa.analyze(self.__image)
			self.__roisArray=[]
			self.__roisArray=rm.getRoisAsArray()
			#for i in range(rm.getCount()) : 
			#	rm.select(i)
			#	rm.runCommand("Set Color", "0000FF", 2)
				
			IJ.resetThreshold(self.__image)
			rt.show("tempRT")
			areas=rt.getColumn(ResultsTable.AREA)
			means=rt.getColumn(ResultsTable.MEAN)
			majors=rt.getColumn(ResultsTable.MAJOR)
			minors=rt.getColumn(ResultsTable.MINOR)
			#print 0
			if self.__slidersDict["Area_max"].getMaximum() <  int(max(areas)+1):
			#	print 1
				self.__slidersDict["Area_max"].setMaximum(int(max(areas))+1)
			if self.__slidersDict["Area_min"].getMaximum() < int(max(areas)+1):
			#	print 2
				self.__slidersDict["Area_min"].setMaximum(int(max(areas))+1)
			if self.__slidersDict["Mean_max"].getMaximum() < int(max(means)+1):
			#	print 3
				self.__slidersDict["Mean_max"].setMaximum(int(max(means))+1)
			if self.__slidersDict["Mean_min"].getMaximum() < int(max(means)+1):
			#	print 4
				self.__slidersDict["Mean_min"].setMaximum(int(max(means))+1)
			if self.__slidersDict["Major_max"].getMaximum() < int(max(majors)):
			#	print 5
				self.__slidersDict["Major_max"].setMaximum(int(max(majors))+1)
			if self.__slidersDict["Major_min"].getMaximum() < int(max(majors)+1):
			#	print 6
				self.__slidersDict["Major_min"].setMaximum(int(max(majors))+1)
			if self.__slidersDict["Minor_max"].getMaximum() < int(max(minors)+1):
			#	print 7
				self.__slidersDict["Minor_max"].setMaximum(int(max(minors))+1)
			if self.__slidersDict["Minor_min"].getMaximum() < int(max(minors)+1):
			#	print 8
				self.__slidersDict["Minor_min"].setMaximum(int(max(minors))+1)
			if self.__slidersDict["AR_max"].getMaximum() < int((max(majors)+1)/min(minors)+1):
			#	print 9
				self.__slidersDict["AR_max"].setMaximum(int((max(majors)+1)/(min(minors))))
			if self.__slidersDict["AR_min"].getMaximum() < int((max(majors)+1)/min(minors)):
			#	print 10
				self.__slidersDict["AR_min"].setMaximum(int((max(majors)+1)/(min(minors))))

			#print 11
				
			for sb in self.__slidersDict.values():
				sb.repaint()

			#rm.runCommand("reset")
			#temprois=self.getIncludeRois()
			#IJ.run(self.__image, "Remove Overlay", "")
			#o=Overlay()
			#for roi in temprois:
			#	o.addElement(roi)
			#self.__image.killRoi()
			#self.__image.setOverlay(o)
			self.__image.updateAndDraw()

		def resetpressed(event):
			self.__ranges.clear()
			self.__image=IJ.getImage()
			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.runCommand("reset")
			self.__image.killRoi()
			IJ.setAutoThreshold(self.__image, "MaxEntropy")
			rt=ResultsTable()
			pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00)
			pa.analyze(self.__image)
			self.__roisArray=[]
			self.__roisArray=rm.getRoisAsArray()
			#rm.runCommand("Show All")
			#rm.runCommand("Select All")
			#rm.runCommand("Set Color", "blue")
			
			IJ.resetThreshold(self.__image)
			
			keys=self.__slidersDict.keys()
			for k in keys:
				if k.endswith("min"): 
					self.__slidersDict[k].setValue(0)
					self.__slidersDict[k].repaint()
				else:
					self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum())
					self.__slidersDict[k].repaint()
			
		def valueChanged(event):
			name=event.getSource().getName()
			names=name.split("_")
			factor=1
			if names[0] in self.__set1000: factor=0.001
			if names[0] in self.__set10:factor=0.1
			value=event.getSource().getValue()*factor
			if names[1]=="min":
				self.__ranges[names[0]]=(names[0], value, self.__slidersDict[names[0]+"_max"].getValue()*factor, self.__boxesDict[names[0]].getState())
				#self.__ranges[names[0]]=(names[0], value, self.__slidersDict[names[0]+"_max"].getValue()*factor)
			else: self.__ranges[names[0]]=(names[0], self.__slidersDict[names[0]+"_min"].getValue()*factor, value, self.__boxesDict[names[0]].getState())
				#self.__ranges[names[0]]=(names[0], self.__slidersDict[names[0]+"_min"].getValue()*factor, value)
			temprois=self.getIncludeRois()
			IJ.run(self.__image, "Remove Overlay", "")
			o=Overlay()
			for roi in temprois:
				o.addElement(roi)
			self.__image.killRoi()
			self.__image.setOverlay(o)
			self.__image.updateAndDraw()

		def selectAll(event):
			name=event.getSource().getLabel()
			names=name.split("_")
			factor=1
			if names[0] in self.__set1000: factor=0.001
			if names[0] in self.__set10:factor=0.1
			name=event.getSource().getLabel()
			names=name.split("_")
			value=event.getSource().getState()
			self.__ranges[names[0]]=(names[0], self.__slidersDict[names[0]+"_min"].getValue()*factor, self.__slidersDict[names[0]+"_max"].getValue()*factor, value)
			

		gd0=NonBlockingGenericDialog("settings")
		gd0.setResizable(True)
		gd0.setFont(Font("Courrier", 1, 8))
		count=0
		self.__slidersDict={}
		self.__boxesDict={}
		self.__boxesDict.clear()
		self.__slidersDict.clear()
		for i in range(len(self.__namemeasures)):
			gd0.setInsets(-10,0,0)			
			gd0.addSlider("Min"+self.__namemeasures[i], 0, self.__maxmeasures[i], 0)
			gd0.getSliders().get(count).adjustmentValueChanged = valueChanged
			gd0.getSliders().get(count).setName(self.__namemeasures[i]+"_min")
			self.__slidersDict[self.__namemeasures[i]+"_min"]=gd0.getSliders().get(count)			
			gd0.addSlider("Max"+self.__namemeasures[i], 0, self.__maxmeasures[i], self.__maxmeasures[i])
			gd0.getSliders().get(count+1).adjustmentValueChanged = valueChanged
			gd0.getSliders().get(count+1).setName(self.__namemeasures[i]+"_max")
			self.__slidersDict[self.__namemeasures[i]+"_max"]=gd0.getSliders().get(count+1)
			gd0.addCheckbox("all", True)
			gd0.getCheckboxes().get(i).itemStateChanged = selectAll
			gd0.getCheckboxes().get(i).setLabel(self.__namemeasures[i]+"_all")
			self.__boxesDict[self.__namemeasures[i]]=gd0.getCheckboxes().get(i)
			gd0.setInsets(-10,0,0)
			#gd0.addMessage("...........................................................................")

			count=count+2
		
		panel0=Panel()
		#trybutton=Button("Try")
		#trybutton.setActionCommand("DrawOverlay")
		#trybutton.actionPerformed = buttonPressed
		#updatebutton=Button("Update")
		#updatebutton.setActionCommand("Update")
		#updatebutton.actionPerformed = updatepressed
		#resetbutton=Button("Reset")
		#resetbutton.setActionCommand("Reset")
		#resetbutton.actionPerformed = resetpressed
		
		
		#panel0.add(trybutton)
		#panel0.add(updatebutton)
		#panel0.add(resetbutton)
		#gd0.addPanel(panel0)

		gd0.setResizable(True) 
		
		gd0.showDialog()
		#self.__image.setSlice(self.__firstslice)
		#self.__image.updateAndDraw()
			
				
		if gd0.wasOKed():
			#for key in self.__ranges.keys(): IJ.log("Measure : "+str(self.__ranges[key][0])+" min = "+str(self.__ranges[key][1])+" max = "+str(self.__ranges[key][2]))
			return self.__ranges
Exemplo n.º 55
0
	def __calRois(self, imp, indice) :									
		"""
		Returns the ROIs of a slice given (identified with its n°) in a stack
		"""
		##imp=self.__dictImages[nameimages]							 		# IL FAUT RÉCUPÉRER L'IMAGE DU STACK !!!!!
		#if self.__batch : imp.hide()
		#else : imp.show()
		#imp.hide()
		imp.show()
		if self.__batch : imp.hide()
		imp.setSlice(indice)
		imp.killRoi()
		ip = imp.getProcessor()

		bs=BackgroundSubtracter() 

		#if str(self.__subback) == "0" or str(self.__subback) == "1" : self.__subback = bool(int(self.__subback))
		#if self.__subback == True : IJ.run(imp, "Subtract Background...", "rolling="+str(self.__radius)+" light")
		if self.__subback == True : bs.rollingBallBackground(ip, self.__radius, False, True, False, True, False)

		if self.__runmacro :
			imp.show()
			imp.setSlice(indice)
			imp.updateAndDraw()
			IJ.runMacroFile(self.__macropath, imp.getTitle())
		
		
			
		imp.updateAndDraw()
		
		#if str(self.__manthresh) == "0" or str(self.__manthresh) == "1" : self.__manthresh = bool(int(self.__manthresh))
		
		#if self.__manthresh : IJ.setThreshold(imp, self.__minthr, self.__maxthr)
		if self.__manthresh : 
			ip.setThreshold(self.__minthr, self.__maxthr, ImageProcessor.RED_LUT)
		else : self.__setThreshold(imp, indice)
		
		rt=ResultsTable()
		pa1=ParticleAnalyzer(ParticleAnalyzer.SHOW_MASKS+ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES , Measurements.AREA, rt, self.__minArea, self.__maxArea, self.__minCirc, self.__maxCirc)
		pa1.setHideOutputImage(True) 
		pa1.analyze(imp)
		
		masks=pa1.getOutputImage()
		masks.getProcessor().erode()
		masks.getProcessor().dilate()
		masks.getProcessor().invertLut()
		masks.getProcessor().threshold(1)
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")
		#rm.hide()
		
		pa2=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET+ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES , Measurements.AREA, rt, self.__minArea, self.__maxArea, self.__minCirc, self.__maxCirc) 
		pa2.analyze(masks)
		masks.close()
		
		temparray=rm.getRoisAsArray()
		for r in temparray :
			tempnameroi=r.getName()
			r.setPosition(indice)
			r.setName(str(indice)+"-"+tempnameroi)
			r.setStrokeWidth(1) 
		
		if len(self.__params) > 0 :
			for k in self.__params:
				#if k[0]=="Area": self.__minArea, self.__maxArea = str(k[1]), str(k[2])
				if k[0]=="Area": self.__minArea, self.__maxArea = k[1], k[2]
			for k in self.__params:
				#if k[0]=="Circ": self.__minCirc, self.__maxCirc = str(k[1]), str(k[2])
				if (k[0]=="Circ") and k[3] : self.__minCirc, self.__maxCirc = k[1], k[2]
				else : self.__minCirc, self.__maxCirc = 0, 1
			self.__rr.setRoisarray(temparray, imp)
			self.__rr.setRange(indice, self.__params)
			return self.__rr.includeRois
		else : return temparray
Exemplo n.º 56
0
		def updatepressed(event):
			self.__image=IJ.getImage()
			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.runCommand("reset")
			self.__image.killRoi()
			IJ.run("Threshold...")
			IJ.setAutoThreshold(self.__image, "MaxEntropy")
			
			rt=ResultsTable()
			pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00)
			pa.analyze(self.__image)
			self.__roisArray=[]
			self.__roisArray=rm.getRoisAsArray()
			#for i in range(rm.getCount()) : 
			#	rm.select(i)
			#	rm.runCommand("Set Color", "0000FF", 2)
				
			IJ.resetThreshold(self.__image)
			rt.show("tempRT")
			areas=rt.getColumn(ResultsTable.AREA)
			means=rt.getColumn(ResultsTable.MEAN)
			majors=rt.getColumn(ResultsTable.MAJOR)
			minors=rt.getColumn(ResultsTable.MINOR)
			#print 0
			if self.__slidersDict["Area_max"].getMaximum() <  int(max(areas)+1):
			#	print 1
				self.__slidersDict["Area_max"].setMaximum(int(max(areas))+1)
			if self.__slidersDict["Area_min"].getMaximum() < int(max(areas)+1):
			#	print 2
				self.__slidersDict["Area_min"].setMaximum(int(max(areas))+1)
			if self.__slidersDict["Mean_max"].getMaximum() < int(max(means)+1):
			#	print 3
				self.__slidersDict["Mean_max"].setMaximum(int(max(means))+1)
			if self.__slidersDict["Mean_min"].getMaximum() < int(max(means)+1):
			#	print 4
				self.__slidersDict["Mean_min"].setMaximum(int(max(means))+1)
			if self.__slidersDict["Major_max"].getMaximum() < int(max(majors)):
			#	print 5
				self.__slidersDict["Major_max"].setMaximum(int(max(majors))+1)
			if self.__slidersDict["Major_min"].getMaximum() < int(max(majors)+1):
			#	print 6
				self.__slidersDict["Major_min"].setMaximum(int(max(majors))+1)
			if self.__slidersDict["Minor_max"].getMaximum() < int(max(minors)+1):
			#	print 7
				self.__slidersDict["Minor_max"].setMaximum(int(max(minors))+1)
			if self.__slidersDict["Minor_min"].getMaximum() < int(max(minors)+1):
			#	print 8
				self.__slidersDict["Minor_min"].setMaximum(int(max(minors))+1)
			if self.__slidersDict["AR_max"].getMaximum() < int((max(majors)+1)/min(minors)+1):
			#	print 9
				self.__slidersDict["AR_max"].setMaximum(int((max(majors)+1)/(min(minors))))
			if self.__slidersDict["AR_min"].getMaximum() < int((max(majors)+1)/min(minors)):
			#	print 10
				self.__slidersDict["AR_min"].setMaximum(int((max(majors)+1)/(min(minors))))

			#print 11
				
			for sb in self.__slidersDict.values():
				sb.repaint()

			#rm.runCommand("reset")
			#temprois=self.getIncludeRois()
			#IJ.run(self.__image, "Remove Overlay", "")
			#o=Overlay()
			#for roi in temprois:
			#	o.addElement(roi)
			#self.__image.killRoi()
			#self.__image.setOverlay(o)
			self.__image.updateAndDraw()
Exemplo n.º 57
0
def run():
	zk = ZeissKeys()
	msg = Message()
	timestart = time.clock()
	channel = 1
	#size in um2
	minArea = 20 
	maxArea = 200
	maxMetaArea = 70
	minMetaAR = 1.8
	method = "Triangle"
	print "Enter run"
	detectionNucleus = [minArea, maxArea]
	detectionMetaphase = [minArea, maxMetaArea]
	filepath = ""
	try:			 
		filepath  = getArgument()
		image = IJ.openImage(filepath) #arguments provided by runMacro
	except NameError:
		try: 
			filepath = newImagePath  #argument provided by the macroRunner
		except NameError: #no file name specified
			errMsg = "Fiji error segmentNuclei.py: no filepath has been passed to the macro"
			exitWithError(errMsg)
			od = OpenDialog("Choose image file", None)
			if od.getFileName() == None:
				return
			filepath = os.path.join(od.getDirectory(), od.getFileName())
	
	# A roimanager is recquired
	roim = RoiManager.getInstance()
	if roim == None:
		roim = RoiManager()
	#test a last time
	if roim == None:
		print 'Fiji error segmentNuclei.py: no RoiManager!'
		exitWithError('Fiji error segmentNuclei.py: no RoiManager!')
		
	try:	
		IJ.run("Close all forced")
		IJ.run("Clear Results")
		IJ.log("\\Clear")
		image = IJ.openImage(filepath)
		IJ.log("File Path  " + filepath)

		
		try: 
			image.hide()
		except: 
			image = IJ.getImage()
			image.hide()
		image.show()	
		if image is None:
			exitWithError("Fiji failed to open image")
			return 0 

		#convert um2 to pixels
		pixelSize = image.getCalibration().pixelWidth
		detectionNucleus = [area/pixelSize/pixelSize for area in detectionNucleus]
		detectionMetaphase = [area/pixelSize/pixelSize for area in detectionMetaphase]
		detectionMetaphase.append(minMetaAR)
		
		title = image.getTitle()
		
		imageC = None
		#split colors if needed
		if image.getNChannels() > 1: 
			chSp = ChannelSplitter()
			imageC = chSp.split(image)
			imageSeg = imageC[channel-1].duplicate()
		else: 
			imageSeg = image.duplicate()
		
		imageSeg.setTitle("SEG_"+title)

				
		sp = segment_Particles()
		imageSeg = sp.preprocessImage(imageSeg, "MAX", "C1", 2, 2)
		imageSeg = sp.segmentParticles(imageSeg, method, detectionNucleus[0], detectionNucleus[1], 2, 2)


		roim = RoiManager.getInstance()
		if roim == None:
			print 'Fiji error segmentNuclei.py: no RoiManager!'
			exitWithError('Fiji error segmentNuclei.py: no RoiManager!')

		#compute central object
		if roim.getCount() > 0:
			centPart, msg.position = centerParticle(imageSeg, roim)
			msg.position = msg.position + (focusParticle(image, roim, centPart),)
			writePositionToRegistry(msg.position)
		else:
			IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ")
			return 0

		#create output image
		if imageC is None:
			impOut = createOutputImg(image, roim, centPart, 0)
		else:
			impOut = createOutputImg(imageC[channel-1], roim, centPart, 0)
		impOut.show()

		#save outut image
		#saveOutputImg(impOut, filepath, 'Analyzed')

		#check for roi properties to identofy metaphase
		metaphase = isSpecialParticle(image, roim, centPart,detectionNucleus, detectionMetaphase,pixelSize, msg.position[2])

		if os.path.basename(filepath).startswith('TR1_') or '_TR1_' in  os.path.basename(filepath):
			metaphase = 0
		if metaphase:
			IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_TRIGGER1+"] windows=REG_SZ")
		else:
			IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_FOCUS+"] windows=REG_SZ")

		IJ.log("time focus " + str(time.clock() - timestart))
		IJ.run("Collect Garbage")
		
		#IJ.run("Close all forced")
		#IJ.run("Clear Results")
		
	except BaseException, err:
Exemplo n.º 58
0
		chimps.append(proj)
		
	return RGBStackMerge.mergeChannels(chimps, False)

manders = MandersColocalization()
results = ResultsTable()
for imageFile in os.listdir(inputDir):
	print "Opening " + imageFile
	try:
		images = BF.openImagePlus(inputDir + imageFile)
		image = images[0]
	except UnknownFormatException:
		continue
	preview = getPreview(image)
	preview.show()
	rm = RoiManager()
	dialog = WaitForUserDialog("Action required", "Please select regions of interest in this image. Click OK when done.")
	dialog.show()
	rm.close()
	splitter = ChannelSplitter()
	imp1 = ImagePlus("CH1", splitter.getChannel(image, imageA))
	imp2 = ImagePlus("CH2", splitter.getChannel(image, imageB))
	title = image.getTitle()
	title = title[:title.rfind('.')]
	image.close()
	preview.close()
	ch1 = ImagePlusAdapter.wrap(imp1)
	ch2 = ImagePlusAdapter.wrap(imp2)

	for roi in rm.getRoisAsArray():
		container = createContainer(roi, ch1, ch2)
Exemplo n.º 59
0
	def showimage(self):
		roim = RoiManager.getInstance()
		if roim is None:
			roim = RoiManager()
		IJ.run("Close All")
		IJ.run("Clear Results")
		try:
			roim.reset()
		except AttributeError:
			roim.runCommand("reset")
		obj = self.fcsimages[self.idximg][0]
		imgName = self.fcsimages[self.idximg][1]

		img =  BF.openImagePlus(imgName)[0]
		img.setZ(obj[1][2]+1)
		img.setC(3)
		IJ.run(img, "Grays", "");
		img.setC(1)
		img.show()

		#draw rois
		for i in range(1, len(obj)+1):
			PR = PointRoi(obj[i][0],obj[i][1])
			try:
				PR.setSize(3)
				PR.setPointType(0)
				roim.addRoi(PR)
			except:
				roim.addRoi(PR)
		roim.runCommand('Show All with Labels')
Exemplo n.º 60
0
	def __settings(self, imgName) :
		"""
		Lets the user to choose different measures to make, and displays it following the choice of the user.
		
		"""

		try : dico=self.__dictCells[imgName]
		except KeyError : 
			try : dico=self.__dictCells[imgName[:-4]]
			except KeyError : return False
			else : imgName=imgName[:-4]
		
		dico=self.__dictCells[imgName]
		for cellname in dico.keys() :
			self.__dictMeasures[dico[cellname]]={}
			
		# Represents the datas on a diagram
		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)
		
		# Represents the datas on a series of graphs.
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")

		#def histbuttonPressed(event) :
		#	
		#	pass

		# Represents the values in a tab.
		def tabbuttonPressed(event) :
		
			tab="\t"
			headings=[]
			measures=[]
			#img=IJ.getImage()
			#for i in range(self.__img.getImageStackSize()+1) :
			for i in range(self.__maxLife+1) :
				headings.append("Slice "+str(i))
			
			headings[0]=WindowManager.getUniqueName(self.__img.getShortTitle())
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				
				headstring=""
				for head in headings: 
					headstring+=head+tab
				tw=TextWindow(self.__listfiles[0]+"-"+m,headstring,"",800,600)
				tp=tw.getTextPanel()
				#for cellname in dico.keys() :
				for cellname in self.__listcellname :
					line=[]
					line=[str(meas)+tab for meas in self.__dictMeasures[dico[cellname]][m]]
					line.insert(0, cellname+tab)
					linestr=""
					for s in line: linestr+=s
					tp.appendLine(linestr)
				tp.updateDisplay()

			if self.__measuresparambool_global[0] :
				tw=TextWindow("Latency","cell\tLatency", "",800,600)
				tp=tw.getTextPanel()
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					tp.appendLine(line)
				tp.updateDisplay() 
				
		def helpbuttonPressed(event) :

			IJ.showMessage("TO DO")

		def newsetPressed(event) :
			gd0.dispose()
			self.__settings()

		def alignbuttonPressed(event) :
			IJ.showMessage("TO DO")


		def mergebuttonPressed(event) :
			IJ.showMessage("TO DO")

		def saveResults() :
			
			#if len(self.__listcellname) == 0 :
			
			nbslices=self.__maxLife
			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time_sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
							
			if not path.exists(self.__rootpath+"Results"+os.path.sep) : os.makedirs(self.__rootpath+os.path.sep+"Results"+os.path.sep, mode=0777)
			tab="\t"
			nl="\n"
			measures=[]
			headstring=""
			#if self.__savemode : mode = "a"
			#else : mode ="w"
			mode = "a"
			
			#for i in range(1, self.__maxLife+1) :headstring += "Slice_"+str(i)+tab
			for i in range(self.__maxLife) :headstring += str(x[i])+tab
			
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				#f.write(m+nl)
				f.write(imgName+"-"+self.__time+"-"+m+"-"+namex+tab+headstring+nl)
				if len(self.__listcellname) == 0 : f.write("no cells")
				else : 
					for cellname in self.__listcellname :
						linestr=cellname+tab
						for measure in self.__dictMeasures[dico[cellname]][m] :
							#print m, cellname, measure 
							linestr += str(measure)+tab
						linestr+=nl
						f.write(linestr)
				f.close()

			if self.__measuresparambool_global[0] :
				m = "Latency"
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				f.write(imgName+"-"+self.__time+"-"+m+nl)
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					line+=nl
					f.write(line)
				f.close()
				
			

			

		#
		# ----------- main measures dialog -------------------------
		#
     		# Allows the user to choose the measures to make, etc..
		
		measureslabels_indep=["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"]
		measureslabels_dep=["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"]
		measureslabels_global=["Latency", "velocity", "cumulatedDist"]
		measureslabels_dep_tabonly=set(["MidAxis","FerCoord","FerAxis","Fprofil","MidProfil","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"])
		ens_measures_global=set(measureslabels_global)
		ens_measures_indep=set(measureslabels_indep)
		ens_measures_dep=set(measureslabels_dep)
		measureslabels=[]
		
		for label in measureslabels_indep :
			measureslabels.append(label)

		for label in measureslabels_dep :
			measureslabels.append(label)

		#self.__defaultmeasures=[False for i in range(len(measureslabels))]
		#self.__defaultmeasures_global=[False for i in range(len(measureslabels_global))]

		gdmeasures=NonBlockingGenericDialog("MeasuresChoice")
		gdmeasures.setFont(Font("Courrier", 1, 10))
		gdmeasures.addMessage("*******     TIME SETTINGS     *******")
		gdmeasures.addCheckbox("Only starting at begining  :", self.__onlystart)				# 1 only start
		gdmeasures.addNumericField("Minimal Lifetime  : ",self.__minLife,0)
		gdmeasures.addNumericField("Maximal Lifetime  : ",self.__maxLife,0)
		#gdmeasures.addNumericField("Maximal Lifetime  : ",self.__img.getImageStackSize(),0)
		gdmeasures.addCheckbox("x axis in seconds", self.__useTime)				# 2 use time
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		gdmeasures.addMessage("Choose the measures to make on the cells : ")			
		gdmeasures.addMessage("*******     TIME MEASURES     *******")
		gdmeasures.addCheckboxGroup(4,8,measureslabels,self.__defaultmeasures)
		gdmeasures.addMessage("")
		gdmeasures.addMessage("*******     GLOBAL MEASURES     *******")
		gdmeasures.addMessage("PLEASE : If you have selected movement parameters you MUST to select XC and YC !")
		gdmeasures.addCheckboxGroup(3,1,measureslabels_global,self.__defaultmeasures_global)
		gdmeasures.addNumericField("Noise value for maxima finder: ",self.__noise,0)
		gdmeasures.addMessage("")	
		gdmeasures.addMessage("*******     OPTIONS     *******")
		gdmeasures.addCheckbox("Select the cells in next dialog ?", self.__onlyselect)			# 3 only select
		gdmeasures.addCheckbox("Save results to text files ?", self.__savetables)			# 4 save files
		#gdmeasures.addCheckbox("Append mode ?", self.__savemode)					# 5 append mode
		gdmeasures.addCheckbox("Analyse in batch mode ?", self.__batchanalyse)				# 6 analysis batch mode
		gdmeasures.addCheckbox("Update overlay ?", self.__updateoverlay)				# 7 update overlay
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		help_panel=Panel()
		helpbutton=Button("HELP")
		helpbutton.actionPerformed = helpbuttonPressed
		help_panel.add(helpbutton)	
		gdmeasures.addPanel(help_panel)	
		gdmeasures.hideCancelButton()

		if not self.__batchanalyse :
			gdmeasures.showDialog()
			self.__onlystart=gdmeasures.getNextBoolean() 						# 1 only start
			self.__minLife=gdmeasures.getNextNumber()
			self.__maxLife=gdmeasures.getNextNumber()
			self.__useTime=gdmeasures.getNextBoolean()						# 2 use time

			self.__measuresparambool=[]
			self.__measuresparambool_global=[]
			for i in range(len(measureslabels)) : 
				self.__measuresparambool.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures[i]=self.__measuresparambool[-1]
			for i in range(len(measureslabels_global)) : 
				self.__measuresparambool_global.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures_global[i] = self.__measuresparambool_global[i]
 
			self.__noise=gdmeasures.getNextNumber()
			self.__onlyselect=gdmeasures.getNextBoolean()						# 3 only select
			self.__savetables = gdmeasures.getNextBoolean()						# 4 save files
			#self.__savemode = gdmeasures.getNextBoolean()						# 5 append mode
			self.__batchanalyse = gdmeasures.getNextBoolean()					# 6 analyse mode
			self.__updateoverlay = gdmeasures.getNextBoolean()					# 7 update overlay

		# we update a list of all cells that have a lifetime corresponding to what the user chose.
		if len (self.__allcells) == 0 :
			for cellname in dico.keys() :
				if dico[cellname].getLifeTime()>=self.__minLife : #and dico[cellname].getLifeTime()<=self.__maxLife :
					if self.__onlystart :
						if dico[cellname].getSlideInit()<2 : self.__allcells.append(cellname)
						else : self.__allcells.append(cellname)

		
		if self.__noise == 0 : self.__noise = None
		if self.__batchanalyse : self.__onlyselect = False
		
		if self.__onlyselect : 
			
			try : 
				self.__gw
			except AttributeError :
				if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
				self.__gw = CellsSelection()
				self.__gw.setTitle(imgName)
				self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
				self.__gw.show()
				self.__gw.setSelected(self.__allcells)
				while not self.__gw.oked and self.__gw.isShowing() : 
					self.__gw.setLabel("Validate selection with OK !!")
					self.__listcellname = list(self.__gw.getSelected())
				self.__gw.resetok()
				self.__gw.setLabel("...")
				self.__gw.hide()
			else : 
				if self.__gw.getTitle() == imgName :
					self.__gw.show()
					self.__gw.setSelected(self.__listcellname)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

				else : 
					self.__gw.dispose()
					if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
					self.__gw = CellsSelection()
					self.__gw.setTitle(imgName)
					self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
					self.__gw.show()
					self.__gw.setSelected(self.__allcells)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

			filestodelet=glob.glob(self.__pathdir+"Selected-Cells"+os.path.sep+"*.cell")
			for f in filestodelet : os.remove(f)
			for cell in self.__listcellname :
				sourcestr = self.__pathdir+"Cells"+os.path.sep+cell+".cell"
				deststr =  self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell"
				#os.system("copy "+sourcestr+", "+deststr) 
				#shutil.copy(self.__pathdir+"Cells"+os.path.sep+cell+".cell",self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell")
				shutil.copy(sourcestr,deststr)

			self.__dictNcells[imgName] = len(self.__listcellname)
		
		else : 
			self.__listcellname = list(self.__allcells)
			self.__dictNcells[imgName] = len(self.__listcellname)

		if len(self.__listcellname) == 0 : 
			self.__dictNcells[imgName] = 0
			return False
		
		self.__img.hide()
		
		# we make the measures.
		for i in range(len(measureslabels)) :
			IJ.showProgress(i, len(measureslabels))
			if  self.__measuresparambool[i]==True :
				
				self.__measurescompl.append(measureslabels[i])
				
				if (measureslabels[i] in measureslabels_dep_tabonly)==False :
					self.__measures.append(measureslabels[i])
				
				if (i<18) and (measureslabels[i] in ens_measures_indep) :
					self.__measureAll(self.__img,measureslabels[i],False, imgName, self.__noise)
					ens_measures_indep.discard(measureslabels[i])
					
				if i>=18 :
					self.__measureAll(self.__img,measureslabels[i],True, imgName, self.__noise)
					
		if self.__measuresparambool_global[0] : # calculate latency
			latencies=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				latencies.append(self.latencie(self.__listcellname[i], self.__img, imgName, self.__useTime))

		if self.__measuresparambool_global[1] : # calculate velocity
			self.__measures.append("velocity")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measureVelocity(self.__img,imgName)

		if self.__measuresparambool_global[2] : # calculate cumulatedDistance
			self.__measures.append("cumulatedDist")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measurecumulDist(self.__img,imgName)	
				
		
		self.__img.show()

		self.__img.getProcessor().resetThreshold()		

		
		if self.__updateoverlay :
			if self.__img.getOverlay() is not None : self.__img.getOverlay().clear()
		
			outputrois=[]
			cellnames=[]
			self.__img.hide()
			for cellname in self.__listcellname :
				
				for r in dico[cellname].getListRoi():
					if isinstance(r,Roi) : 
						pos=r.getPosition()
						#print "MC overlay", cellname, r.getName(), pos
						#r.setPosition(0)
						#overlay.add(r)
						outputrois.append(r)
						if "cell" in r.getName() : cellnames.append(r.getName())
						else : cellnames.append(str(pos)+"-"+cellname)
						#print cellnames[-1]

			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.show()
			self.__img.show()
			IJ.selectWindow(self.__img.getTitle())
			rm.runCommand("reset")
			for i in range(len(outputrois)) :
				outputrois[i].setName(cellnames[i])
				rm.addRoi(outputrois[i])
				rm.select(rm.getCount()-1)
				rm.runCommand("Rename", cellnames[i])
			
			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(self.__img, "Labels...", "color=red font=12 show use")
			IJ.run(self.__img, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")


		# ----------- batch analyse ------------------------
		if self.__batchanalyse :
			if self.__savetables :  saveResults()
			self.__dictMeasures.clear()
     			self.__allcells[:]=[]
     			self.__measurescompl[:]=[]
     			self.__measures[:]=[] 
			return False
			
		# ---------- display methodes dialog ----------------
		# Allows the user to choose how to see the results of the measures.		
		
		gd0=NonBlockingGenericDialog("Display")

		gd0.addMessage("How do you want to see the results ?")
		
		panel0=Panel()
		
		diagrambutton=Button("Diagram")
		diagrambutton.actionPerformed = diagrambuttonPressed
		panel0.add(diagrambutton)

		graphbutton=Button("Graph")
		graphbutton.actionPerformed = graphbuttonPressed
		panel0.add(graphbutton)

		tabbutton=Button("Tab")
		tabbutton.actionPerformed = tabbuttonPressed
		panel0.add(tabbutton)
		gd0.addPanel(panel0)
		gd0.addCheckbox("Analyse next stack ?", self.__nextstack)
		gd0.hideCancelButton()	
		gd0.showDialog()

		self.__nextstack = gd0.getNextBoolean()

		# ---------- save tables ---------------------------
		if self.__savetables :  saveResults()
		
		# --------- re-start analysis -------------------
		
     		self.__dictMeasures.clear()
     		#self.__listcellname[:]=[]
     		self.__allcells[:]=[]
     		self.__measurescompl[:]=[]
     		self.__measures[:]=[]

     		if self.__nextstack : return False
     		else : return True