Example #1
0
    def creating_vor_roi(self):
        """
        runs voronoi on cell to create vor_rois
        """
        rm = RoiManager.getRoiManager()
        rm.reset()
        d = Duplicator()
        nuc_bin_copy = d.run(self.hseg.nuc_bin())
        nuc_bin_copy.show()

        IJ.run(nuc_bin_copy, "Make Binary", "")
        nuc_bin_copy.setRoi(self.roi())
        IJ.run(nuc_bin_copy, "Clear Outside", "")

        # 1/0

        IJ.run(nuc_bin_copy, "Voronoi", "")
        nuc_bin_copy.setRoi(None)
        ip = nuc_bin_copy.getProcessor()
        ip.setMinAndMax(0, 1)
        IJ.run(nuc_bin_copy, "Apply LUT", "")

        nuc_bin_copy.setRoi(self.roi())
        IJ.run(nuc_bin_copy, "Analyze Particles...", "add")
        vor_rois = rm.getRoisAsArray()

        # self.hseg.raw_stack().show()
        # 10/0

        futils.force_close(nuc_bin_copy)

        return vor_rois
Example #2
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
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")
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]
Example #5
0
def measure_roi_set(roi_set, imp, set_measure=MEAS_ALL) :
    """requires imp because it won't measure without one
    note.. side effects: ResultsTable and RoiManager cleared"""
    # imp.show()
    rt = ResultsTable.getResultsTable()
    rt.reset()

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


    if roi_set is not None :

        for roi in roi_set :
            add_roi(roi)

    rm.setSelectedIndexes([x for x in range(rm.getCount())])
    setMeasurementInt(set_measure)
    print("before rm measure")
    # IJ.setActiveImage(imp)
    # IJ.selectWindow(imp.getTitle())
    # imp.show()
    try :
    # input()
    # for roi in roi_set :
        # imp.
        rm.runCommand(imp, "Measure")
    except :
        input()
    print("after rm measure")

    results = rt_to_col_dict()
    # imp.hide()
    return results
Example #6
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()
    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()
Example #8
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
Example #9
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)
Example #10
0
    def match_vor_nuc(self, vor_rois):
        """
            matches vor_rois with their respective nucs
            by checking if nuc_cent in vor_roi

            currently having issues/not working
        """
        ## if IJ.escapePressed() : IJ.exit()
        ## did this work?

        rm = RoiManager.getRoiManager()
        nuc_inds = [x for x in range(len(self.nucs()))]
        for vor_roi in vor_rois:

            temp = None
            for i, nuc_ind in enumerate(nuc_inds):
                nuc_roi = self.nucs()[nuc_ind].roi()

                nuc_cent = futils.roi_cent(nuc_roi, integer=True)

                if vor_roi.contains(*nuc_cent):
                    self.nucs()[nuc_ind]._vor_roi = vor_roi

                    temp = i
                    break

            else:

                raise BobException('{}: issue matching voronoi and nuc'.format(
                    self.hseg.name))

            if temp is not None:
                del nuc_inds[temp]
Example #11
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])
Example #12
0
def vor_cell(nuc_bin_imp, cell):
    """creates the voronoi for one cell, cell is assumed to have nucs"""

    rm = RoiManager.getRoiManager()
    rm.reset()
    d = Duplicator()
    nuc_bin_copy = d.run(nuc_bin_imp)

    IJ.run(nuc_bin_copy, "Make Binary", "")
    nuc_bin_copy.setRoi(cell.roi)
    IJ.run(nuc_bin_copy, "Clear Outside", "")

    IJ.run(nuc_bin_copy, "Voronoi", "")

    nuc_bin_copy.setRoi(None)
    ip = nuc_bin_copy.getProcessor()
    ip.setMinAndMax(0, 1)
    IJ.run(nuc_bin_copy, "Apply LUT", "")
    IJ.run(nuc_bin_copy, "Invert", "")

    nuc_bin_copy.setRoi(cell.roi)
    IJ.run(nuc_bin_copy, "Analyze Particles...", "add")
    vor_rois = rm.getRoisAsArray()

    nuc_inds = [x for x in range(len(cell.nucs))]
    for vor_roi in vor_rois:

        temp = None
        for i, nuc_ind in enumerate(nuc_inds):
            nuc_roi = cell.nucs[nuc_ind].roi

            nuc_cent = roi_cent(nuc_roi, integer=True)

            if vor_roi.contains(*nuc_cent):
                cell.nucs[nuc_ind].vor_roi = vor_roi
                ## I don't think I need to do this, I could just use i outside of loop but it feels so insecure or something
                temp = i
                break

        else:
            IJ.log('cell: {}, issue with voronoi nuc match up'.format(
                cell.name))
            rm.reset()
            for i, nuc in enumerate(cell.nucs):

                x = int(nuc.roi.getXBase())
                y = int(nuc.roi.getYBase())
                IJ.log('{}. ({},{})'.format(i, x, y))
                add_roi(Roi(x, y, 10, 10), str(i))
            IJ.log(str(nuc_inds))
            add_roi(vor_roi, "vor_roi")

            ## raise RuntimeError('cell: {}, issue with voronoi nuc match up'.format(cell.name))

        if temp is not None:
            del nuc_inds[temp]

    force_close(nuc_bin_copy)
Example #13
0
def roi_name_index_dict() :
    """create and return a dict that takes an image_name(str) and returns it's index(int)
    image_name or roi_name??"""
    rm = RoiManager.getRoiManager()

    str_ind_dict = {}
    for i in range(rm.getCount()) :
        str_ind_dict[rm.getName(i)] = i
    return str_ind_dict
Example #14
0
def add_roi(roi, name=None) :
    """add roi to RoiManager, if name is given, sets its name to name"""
    rm = RoiManager.getRoiManager()
    # print(rm)
    # rm.show()
    rm.addRoi(roi)
    # print('fiji_utils.add_roi: {}: {}'.format(name, roi))
    if name is not None :
        rm.rename(rm.getCount() - 1, name)
Example #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))
Example #16
0
def disp_hseg(hseg):
    """display images of hseg and adds rois of hseg to RoiManager"""
    if True:
        RoiManager.getRoiManager().reset()

    hseg.raw_imp.show()
    hseg.nuc_bin_imp.show()

    for cell in hseg.cells.values():
        add_roi(cell.roi, name=cell.name)

        for i, nuc in enumerate(cell.nucs):
            add_roi(nuc.roi, name='{} nuc {}'.format(cell.name, i))

        for i, nuc in enumerate(cell.nucs):
            add_roi(nuc.vor_roi, name='{} vor {}'.format(cell.name, i))

    for name, cell in hseg.cells.items():
        add_roi(cell.roi, name=name)
Example #17
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"
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])
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")
Example #20
0
def setup():
    """setup"""
    ## set setting to save column headers
    IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv use_file save_column")

    ## set setting to copy column headers - not actually necessary
    IJ.run("Input/Output...",
           "jpeg=85 gif=-1 file=.csv copy_column save_column")

    force_close_all_images()
    rm = RoiManager.getRoiManager()
    rm.reset()
    rm.show()
Example #21
0
    def removeOrphansSegments(self, orphans, debug=False, verbose=False):
        rm = RoiManager.getRoiManager()

        for o in orphans:
            if o in self.segments:
                if verbose:
                    print("Orphan " + o.ID + " removed!")
                self.segments.remove(o)
                for index in range(rm.getCount() - 1):
                    if rm.getName(index) == o.ID:
                        break

                rm.select(index)
                rm.runCommand("Delete")
Example #22
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))
Example #23
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)]
Example #24
0
def RoiEroder(pixels):
   RM = RoiManager()        # we create an instance of the RoiManager class
   rm = RM.getRoiManager()  # "activate" the RoiManager otherwise it can behave strangely

   rm.reset()

   # Re-open temporary original ROIs
   temp_roi_path = gvars['tempFile']
   rm.runCommand("Open", temp_roi_path)
   print "Temp ROIs OPENED"

   for i in range(0, rm.getCount()):
      roi = rm.getRoi(i)
      new_roi = RoiEnlarger.enlarge(roi, -pixels) # Key to use this instead of the IJ.run("Enlarge... much faster!!
      rm.setRoi(new_roi,i)

   gvars['eroded_pixels'] = pixels # Store globally the amount of pixels used to later save them in the ROI file name
Example #25
0
def open_get_roi(roi_path) :
    """open or get roi - uses filename for the roi in RoiManager"""
    rm = RoiManager.getRoiManager()
    roi_name_to_index = roi_name_index_dict()

    roi_name = os.path.basename(roi_path)

    if roi_name in roi_name_to_index :
        roi = rm.getRoi(roi_name_to_index[roi_name])
    else :

        IJ.openImage(roi_path)
        imp = IJ.getImage()

        roi = imp.getRoi()
        add_roi(roi, roi_name)

    return roi
Example #26
0
def measure_roi_set(roi_set, imp, set_measure=MEAS_ALL):
    """requires imp because it won't measure without one
	note.. side effects: ResultsTable and RoiManager cleared"""

    rt = ResultsTable.getResultsTable()
    rt.reset()

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

    for roi in roi_set:
        add_roi(roi)

    setMeasurementInt(set_measure)
    rm.runCommand(imp, "Measure")
    results = rt_to_col_dict()

    return results
Example #27
0
 def colorizeRoisBySubtree(self):
     roiManager = RoiManager.getRoiManager()
     colors = {
         0: "red",
         1: "green",
         2: "blue",
         3: "yellow",
         4: "magenta",
         5: "cyan",
         6: "orange",
         7: "black",
         8: "white"
     }
     currentColor = 0
     for subtree in self.children:
         for spot in subtree.flatten():
             roiManager.select(spot.spotID - 1)
             roiManager.runCommand("Set Color", colors[currentColor])
         currentColor = (currentColor + 1) % len(colors)
def main():

	# Get source and destination paths
	srcDir = srcFile.getAbsolutePath()
	dstDir = dstFile.getAbsolutePath()
	# Check to see source and destination paths exist
	if os.path.exists(srcDir) and os.path.exists(dstDir):

		# Get date and time for CSV naming
		localtime = time.localtime(time.time())
		timef = "{0:4d}{1:02d}{2:02d}_{3:02d}{4:02d}{5:02d}".format(localtime.tm_year, localtime.tm_mon, localtime.tm_mday, localtime.tm_hour, localtime.tm_min, localtime.tm_sec)
		# Reshape for inside of CSV file
		date = "{0:4d}-{1:02d}-{2:02d}".format(localtime.tm_year, localtime.tm_mon, localtime.tm_mday)
		
		# initialize the CSV
		pathCSV = UrchinFF.initializeCSV(timef, dstDir)

		# Open roi Manager
		rm = RoiManager.getRoiManager()
		IJ.log("RoiManger opened...")
		
		# walk through the source directory
		for root, directories, filenames in os.walk(srcDir):
			filenames.sort();
			for filename in filenames:
				filenameDown = filename.lower()
				extDown = ext.lower()
				if filenameDown.endswith(extDown):
					# Open image
					tempPath = os.path.join(srcDir, filename)
					imp = IJ.openImage(tempPath)
					results = UrchinProcess.process(imp)
					IJ.log("Results: " + str(results))
					
					imp.close()
					### Save data ###
					UrchinFF.appendNewRow(pathCSV, filename, date, results)
				
	else:
		IJ.log("Source or destination directorty do not exists")

	IJ.log("UrchinPy is done!")
Example #29
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
Example #30
0
def measure_roi_dict(imp, roi_dict, set_measure=MEAS_ALL) :
    # imp.show()
    rt = ResultsTable.getResultsTable()
    rt.reset()

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

    for roi_name, roi in roi_dict.items() :
        add_roi(roi, name=roi_name)

    rm.setSelectedIndexes([x for x in range(rm.getCount())])
    setMeasurementInt(set_measure)

    ## imp.show()

    rm.runCommand(imp, "Measure")

    results = rt_to_col_dict()
    # imp.hide()
    return results
Example #31
0
    def setup() :
        """setup"""

        if Exper.IN_DEV :
            canceled = False
        else :
            canceled = not IJ.showMessageWithCancel(__program__,'To proceed program will close all open images and windows, continue?')

        if not canceled :
            IJ.run("Colors...", "foreground=white background=black selection=yellow");

            ## aspirational todo: identify current settings and return settings at the end
            ## set setting to save column headers
            IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv use_file save_column");

            ## set setting to copy column headers - not actually necessary
            IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv copy_column save_column");

            futils.force_close_all_images()
            rm = RoiManager.getRoiManager()
            rm.reset()
            rm.show()
Example #32
0
def runScript(nCols, nRows, circRad):
    print('___Running Blobber___')

    circXUpLeft = 33.
    circYUpLeft = 915.
    circXUpRight = 1033.
    circYUpRight = 627.
    circXLowLeft = 95.
    circYLowLeft = 1125.

    imp = IJ.getImage()
    nSlices = imp.getNSlices()
    print('The image has {} slices'.format(nSlices))

    circXUpLeft, circYUpLeft = getEdgeCoord(circXUpLeft, circYUpLeft, circRad,
                                            imp, 'Upper Left')
    print('upper left x,y: {},{}'.format(circXUpLeft, circYUpLeft))
    circXUpRight, circYUpRight = getEdgeCoord(circXUpRight, circYUpRight,
                                              circRad, imp, 'Upper Right')
    print('upper right x,y: {},{}'.format(circXUpRight, circYUpRight))
    circXLowLeft, circYLowLeft = getEdgeCoord(circXLowLeft, circYLowLeft,
                                              circRad, imp, 'Lower Left')
    print('lower left x,y: {},{}'.format(circXLowLeft, circYLowLeft))

    hOffsetY = (circYUpRight - circYUpLeft) / (nCols - 1)
    hOffsetX = (circXUpRight - circXUpLeft) / (nCols - 1)
    vOffsetY = (circYLowLeft - circYUpLeft) / (nRows - 1)
    vOffsetX = (circXLowLeft - circXUpLeft) / (nRows - 1)

    x, y = createArrayCoord(hOffsetX, hOffsetY, vOffsetX, vOffsetY, nCols,
                            nRows, circXUpLeft, circYUpLeft)
    RM = RoiManager()
    rm = RM.getRoiManager()
    imp, rm = makeSelections(x, y, rm, imp, circRad)
    imp, rm = measureSelections(imp, rm, nCols, nRows)
    IJ.run(imp, "Select None", "")