Ejemplo n.º 1
0
def getSettings(img):
    """This function assesses (by returning a boolean value) if the filter can
    be applied to the image passed as argument. Will ask the user for new values
    if current parameters are undefined."""
    global xradius, yradius, zradius
    canProceed = True

    if not img:
        IJ.error("No images open.")
        canProceed = False

    # Get new values if at least one of the parameters is 'null'
    if canProceed and None in (xradius, yradius, zradius):
        gd = GenericDialog("Median Filter")
        gd.addNumericField("X radius:", 2.0, 1)
        gd.addNumericField("Y radius:", 2.0, 1)
        gd.addNumericField("Z radius:", 2.0, 1)
        gd.showDialog()
        if gd.wasCanceled():
            canProceed = False
        else:
            xradius = gd.getNextNumber()
            yradius = gd.getNextNumber()
            zradius = gd.getNextNumber()
 
    return canProceed
def run():
    ''' If someone tries to run this file by itself, warn them of their error.  Unfortunately, since I was too lazy to make Microscope_Calibrations a full plugin (rather than a script), this accompanying settings file will show up in the Scripts menu.'''
    from ij.gui import GenericDialog
    
    gd = GenericDialog("Microscope_Calibrations_user_settings.py")
    gd.addMessage("This file is only for adding functionality to the plugin 'Microscope Measurement Tools'.\nNothing is done when this settings file is run by itself."  )
    
    gd.showDialog()
Ejemplo n.º 3
0
def run():
    srcDir = IJ.getDirectory("Input_directory")
    if not srcDir:
        return
    gd = GenericDialog("Do you want to run the image correction now?")
    gd.showDialog()
    if gd.wasCanceled():
        return
    find_folders(srcDir)
Ejemplo n.º 4
0
def choose_analysis_mode(params):
    """present UI for choosing how cells should be identified"""
    dialog = GenericDialog("Analysis methods")
    dialog.addMessage("Please choose how cell shape anlaysis should proceed:")
    dialog.addChoice("Analysis mode", params.list_analysis_modes(),
                     params.last_analysis_mode)
    dialog.showDialog()
    if dialog.wasCanceled():
        raise KeyboardInterrupt("Run canceled")
    return dialog.getNextChoice()
def run():
    ''' If someone tries to run this file by itself, warn them of their error.  Unfortunately, since I was too lazy to make Microscope_Calibrations a full plugin (rather than a script), this accompanying settings file will show up in the Scripts menu.'''
    from ij.gui import GenericDialog
    
    gd = GenericDialog("Microscope_Calibrations_user_settings.py")
    gd.addMessage("This file is only for setting the microscope calibrations and settings for the plugins 'Microscope Measurement Tools'.\nNothing is done when this settings file is run by itself.\nPlease open this file in a text editor instead, to edit the calibrations.\n  \n"  +  \
    "The file should reside in a path like the following\n"  +  \
    "Fiji.app/plugins/Scripts/Analyze/Microscope Measurement Tools/Microscope_Calibrations_user_settings.py\n  "  +  "\n" +  \
    "Changes to the settings file are not automatically picked up by Fiji.  The workaround is to\n  1) Quit Fiji.\n  2) Delete the '$py.class' file 'Microscope_Calibrations_user_settings$py.class'\n  3) Open Fiji.  Make sure the new settings show up in 'Choose Microscope Calibration'."  )
    
    gd.showDialog()
def getOptions():
	gd = GenericDialog("Option")
	gd.addNumericField("Sliding Z Projection Slices", 5, 0) # show 0 decimals
	gd.addHelp("http://www.robertcudmore.org/software/bSliding_Z_Projection.html")
	gd.showDialog()

	if gd.wasCanceled():
		print "User cancelled dialog."
		return
	#read out options
	userSlices = gd.getNextNumber()
	return int(userSlices)
Ejemplo n.º 7
0
def getMinMaxFor8Bit(minMaxs):
	gd = GenericDialog('Enter the min and max for each channel for the 8 bit transformation')
	for channel in minMaxs.keys():
		gd.addNumericField('Min ' + channel , minMaxs[channel][0], 2) # show 2 decimals
		gd.addNumericField('Max ' + channel, minMaxs[channel][1], 2)
	gd.showDialog()
	if gd.wasCanceled():
		IJ.log('User canceled dialog!')
		return
	for channel in minMaxs.keys():
		minMaxs[channel][0] = gd.getNextNumber()
		minMaxs[channel][1] = gd.getNextNumber()
	return minMaxs
	def showOptionsDialog(self):
		gd = GenericDialog("my cool tool options")
		gd.addNumericField("min. size: ", self.minSize)
		gd.showDialog()
		if gd.wasCanceled():
			return None
		self.minSize = gd.getNextNumber()
Ejemplo n.º 9
0
def optionsDialog():
	gd = GenericDialog('bPrairie2tif options')

	# label, value, digits
	gd.addNumericField('Median Filter Pixel Size (0 for no filtering)', globalOptions['medianFilter'], 0)
	gd.addCheckbox('Convert to 8 bit', globalOptions['convertToEightBit'])
	
	gd.showDialog()
	if gd.wasCanceled():
		return None

	globalOptions['medianFilter'] = gd.getNextNumber()
	globalOptions['convertToEightBit'] = gd.getNextBoolean()

	return 1
Ejemplo n.º 10
0
def getName(text, defaultName = ''):
	gd = GenericDialog(text)
	gd.addStringField(text, defaultName)
	gd.showDialog()
	if gd.wasCanceled():
		print 'User canceled dialog!'
		return
	return gd.getNextString()
Ejemplo n.º 11
0
def getRefChannel(channels, text = 'Reference Channel'): #dialog prompt to choose the reference channel
	gd = GenericDialog(text)
	gd.addChoice("output as", channels, channels[0])
	gd.showDialog()
	if gd.wasCanceled():
		print "User canceled dialog!"
		return
	return gd.getNextChoice()
Ejemplo n.º 12
0
def getNumber(text, default = 0, decimals = 3):
	gd = GenericDialog(text)
	gd.addNumericField(text, default, decimals)  # show 6 decimals
	gd.showDialog()
	if gd.wasCanceled():
		IJ.log('User canceled dialog!')
		return
	return gd.getNextNumber()
Ejemplo n.º 13
0
	def edit(self, msg=""):
		'''
		Opens the color tags dialog to update color tags
		'''
		self.window = GenericDialog("ColorMerger - Edit color tags")
		self.window.addMessage("{0}Separate tags with a comma.\nBlank values will be ignored.".format(msg))
		for i in range(7):
			try:
				self.window.addStringField(COLORS[i], ", ".join(self.tags[i]), 30)
			except KeyError:
				self.window.addStringField(COLORS[i], "", 30)
		self.window.setOKLabel("Save")
		self.window.showDialog()
		if self.window.wasOKed():
			self.__savetags()
			self.load()
def canceled():
    gd = GenericDialog("Caution")
    gd.addMessage('Tiff file(s) already exists in {}.\n \
    The file may be replaced by this macro run. Do you wish to continue?'.
                  format(save_dir))
    gd.showDialog()
    return gd.wasCanceled()
Ejemplo n.º 15
0
def getChannels():
	gd = GenericDialog( "Select stack's channels" )
	# print gd.getModalityType() 
	# gd.setModal( False )
	# print gd.getModalityType() 
	color = ["red", "green", "blue"]
	gd.addChoice("Channel for mask", color, color[2])
	gd.addChoice("Channel for particles", color, color[1])
	gd.showDialog()
	maskChannel = gd.getNextChoice()  
	partChannel = gd.getNextChoice()  
	if gd.wasCanceled():  
		sys.exit()
	return maskChannel, partChannel
Ejemplo n.º 16
0
	def inputScale(self):
		gd=GenericDialog("Scale ROI")
		gd.addStringField("X Scale:",str(self.xScale))
		gd.addStringField("Y Scale:",str(self.yScale))
		gd.addStringField("Scale X to pixel:",str(self.impXpixel))
		gd.addStringField("Scale Y to pixel:",str(self.impYpixel))
		fields=gd.getStringFields()
		self.XscaleField,self.YscaleField=fields[0],fields[1]
		self.toXfield,self.toYfield=fields[2],fields[3]
		self.XscaleField.addTextListener(self)
		self.YscaleField.addTextListener(self)
		self.toXfield.addTextListener(self)
		self.toYfield.addTextListener(self)
		gd.showDialog()
		if gd.wasOKed():
			return(self.xScale,self.yScale)
		else:
			return(1.0,1.0)
def getPixel(
):  # Get pixel size from user with dialog box. could return python dict or make custom class? Note user can return a NaN if doesnt enter numeric
    gd = GenericDialog("Pixel")
    gd.addNumericField("Pixel size desired (mm)", 6.4,
                       1)  # default is 1 decimal
    gd.showDialog()
    Pixel_size = gd.getNextNumber(
    )  #6.4 # ENTER mm, remember tolerance is +/-30%
    return Pixel_size
	def _dialog(self,comment):
		gd = GenericDialog(comment)
		gd.enableYesNoCancel()
		gd.showDialog()
		if gd.wasCanceled():
			print "user cancelled dialog"
			sys.exit(1)
			
		option = gd.wasOKed()
		return option
Ejemplo n.º 19
0
def get_results_filename():
    '''Prompt the user to suggest name of the output file.'''
    dialog = GenericDialog('Output results file')
    dialog.addStringField('Choose name without extension:', 'results')
    dialog.showDialog()
    name = dialog.getNextString()
    if dialog.wasCanceled():
        return None
    #TODO Check if file exists before and try again?
    return name + '.csv'
def choose_series(filepath, params):
	"""if input file contains more than one image series (xy position), prompt user to choose which one to use"""
	# todo: if necessary (e.g. if lots of series), can improve thumbnail visuals based loosely on https://github.com/ome/bio-formats-imagej/blob/master/src/main/java/loci/plugins/in/SeriesDialog.java
	import_opts = ImporterOptions();
	import_opts.setId(filepath);
	
	reader = ImageReader();
	ome_meta = MetadataTools.createOMEXMLMetadata();
	reader.setMetadataStore(ome_meta);
	reader.setId(filepath);
	no_series = reader.getSeriesCount();
	if no_series == 1:
		return import_opts, params;
	else:
		series_names = [ome_meta.getImageName(idx) for idx in range(no_series)];
		dialog = GenericDialog("Select series to load...");
		dialog.addMessage("There are multiple series in this file! \n" + 
						"This is probably because there are multiple XY stage positions. \n " + 
						"Please choose which series to load: ");
		thumbreader = BufferedImageReader(reader);
		cbg = CheckboxGroup();
		for idx in range(no_series):
			p = Panel();
			p.add(Box.createRigidArea(Dimension(thumbreader.getThumbSizeX(), thumbreader.getThumbSizeY())));
			ThumbLoader.loadThumb(thumbreader, idx, p, True);
			dialog.addPanel(p);
			cb = Checkbox(series_names[idx], cbg, idx==0);
			p.add(cb);

		dialog.showDialog();
		if dialog.wasCanceled():
			raise KeyboardInterrupt("Run canceled");
		if dialog.wasOKed():
			selected_item = cbg.getSelectedCheckbox().getLabel();
			selected_index = series_names.index(selected_item);
			params.setSelectedSeriesIndex(selected_index);
			for idx in range(0, no_series):
				import_opts.setSeriesOn(idx, True) if (idx==selected_index) else import_opts.setSeriesOn(idx, False);
	reader.close();
	return import_opts, params
Ejemplo n.º 21
0
def create_selection_dialog(image_titles, defaults, title='Select images for processing'):
    gd = GenericDialog(title)
    # The build in function enumerate() returns two values:
    # The index and the value stored in the tuple/list.
    for index, default in enumerate(defaults):
        # for each loop we add a new choice element to the dialog.
        gd.addChoice('Image_'+ str(index + 1), image_titles, image_titles[default])
    gd.showDialog()
    if gd.wasCanceled():
        return None
    # This function returns a list.
    # _ is used as a placeholder for values we don't use.
    # The for loop is used to call gd.getNextChoiceIndex() len(defaults) times.
    return [gd.getNextChoiceIndex() for _ in defaults]
Ejemplo n.º 22
0
    def openNext(self):
        """
        Opens the next image.

        Arguments:
        - thumbNails : bool, if True a thumbnail for th
          image is written when the image is opened
        """
        self.openImage.close()
        # Set the current number being examined
        self.n = self.n + 1
        try:
            self.currentCoordinate = self.gridCoords[ self.n ]
        except IndexError:
            gd = GenericDialog("")
            gd.addMessage("No more images")
            gd.showDialog()
            return None
        plateID, row, col, x, y = self.currentCoordinate
        # open the file
        grid = self.grids[ plateID ]
        self.openImage = grid.openSubImage(x,y)
        self.setMinAndMax()
        self.openImage.show()
        # Write the thumbnail
        self.writeThumbnail()
        # Try to return the information about the current score
        # if it doesn't exist, return an empty string. This
        # is used to display the score associated with the image
        try:
            return self.scores[ self.currentCoordinate ][7]
        except KeyError:
            return ""
Ejemplo n.º 23
0
def run():
    ''' If someone tries to run this file by itself, warn them of their error.  Unfortunately, since I was too lazy to make Microscope_Calibrations a full plugin (rather than a script), this accompanying settings file will show up in the Scripts menu.'''
    from ij.gui import GenericDialog
    
    gd = GenericDialog("Microscope_Calibrations_user_settings.py")
    gd.addMessage("This file is only for adding functionality to the plugin 'Microscope Measurement Tools'.\nNothing is done when this settings file is run by itself."  )
    
    gd.showDialog()
Ejemplo n.º 24
0
def Resize(imp):
	gd = GenericDialog("Image size")
	scales = ["1024","2048","4096"]
	gd.addChoice("Choose image size",scales,scales[1])
	gd.showDialog()
	scale_choice = gd.getNextChoice()
	IJ.run(imp,"Scale...", "x=- y=- z=1.0 width="+scale_choice+" height="+scale_choice+" interpolation=Bilinear average process create title=Scaled")
	scaled_imp = WindowManager.getImage("Scaled")
	return scaled_imp
def create_selection_dialog(image_titles, defaults, title='Select images for processing'):
    gd = GenericDialog(title)
    # The build in function enumerate() returns two values:
    # The index and the value stored in the tuple/list.
    for index, default in enumerate(defaults):
        # for each loop we add a new choice element to the dialog.
        gd.addChoice('Image_'+ str(index + 1), image_titles, image_titles[default])
    gd.showDialog()
    if gd.wasCanceled():
        return None
    # This function returns a list.
    # _ is used as a placeholder for values we don't use.
    # The for loop is used to call gd.getNextChoiceIndex() len(defaults) times.
    return [gd.getNextChoiceIndex() for _ in defaults]
Ejemplo n.º 26
0
 def getRef(self, event):
     """ Dialog to update ref image attribute when get_ref button is pressed """
     self.checkImages()
     gd = GenericDialog("Choose a reference image")
     gd.addChoice("Reference image",
                  [Image.title for Image in self.Images.values()],
                  self.Images.values()
                  [0].title)  # add all Image instances to a drop-down list
     gd.showDialog()
     ref_image_name = gd.getNextChoice()
     ref_image_ID = WM.getImage(ref_image_name).getID()
     self.ref_image = self.Images[
         ref_image_ID]  # update ref_image attribute
     IJ.log("Reference image is " + self.ref_image.title)
Ejemplo n.º 27
0
def run():
    ''' If someone tries to run this file by itself, warn them of their error.  Unfortunately, since I was too lazy to make Microscope_Calibrations a full plugin (rather than a script), this accompanying settings file will show up in the Scripts menu.'''
    from ij.gui import GenericDialog

    gd = GenericDialog("Microscope_Calibrations_user_settings.py")
    gd.addMessage("This file is only for setting the microscope calibrations and settings for the plugins 'Microscope Measurement Tools'.\nNothing is done when this settings file is run by itself.\nPlease open this file in a text editor instead, to edit the calibrations.\n  \n"  +  \
    "The file should reside in a path like the following\n"  +  \
    "Fiji.app/plugins/Scripts/Analyze/Microscope Measurement Tools/Microscope_Calibrations_user_settings.py\n  "  +  "\n" +  \
    "Changes to the settings file are not automatically picked up by Fiji.  The workaround is to\n  1) Quit Fiji.\n  2) Delete the '$py.class' file 'Microscope_Calibrations_user_settings$py.class'\n  3) Open Fiji.  Make sure the new settings show up in 'Choose Microscope Calibration'."  )

    gd.showDialog()
Ejemplo n.º 28
0
def get_config_file(folder):
    '''Returns the config file name.'''
    # Get list of files in the selected directory.
    files = os.listdir(folder)

    # Check if a config file is present in folder.
    if default_config in files:
        dialog = GenericDialog('Default config file found!')
        dialog.addMessage('Use this file for the analysis?\n \n%s' % os.path.join(folder, default_config))
        dialog.enableYesNoCancel()
        dialog.showDialog()
        if dialog.wasCanceled():
            return None
        elif dialog.wasOKed():
            return default_config
        else:
            open_dialog = OpenDialog('Select a config file', folder, default_config)
            return open_dialog.getFileName()
    else:
        # Ask user to select a config file.
        open_dialog = OpenDialog('Select a config file', folder, default_config)
        return open_dialog.getFileName()
Ejemplo n.º 29
0
 def showTable(self):
     """
     Create the GUI and show it.  For thread safety,
     self method should be invoked from the
     event-dispatching thread.
     """
     gd = GenericDialog("Roi-group table")
     gd.addPanel(
         self
     )  # Add current table instance (a subclass of Panel to gd panel)
     gd.showDialog()
Ejemplo n.º 30
0
def create_selection_dialog(image_titles, defaults, title='Select images for processing'):
    """
    Show a dialog to select the images to process and return a list of the selected ones (index).
    :param image_titles: A list of image titles presented for selection.
    :param defaults: The titles to be selected by default.
                     The length of this list defines the number of selectable images.
    :param title: the title of the dialog (default 'Select images for processing').
    """
    dialog = GenericDialog(title)
    for index, default in enumerate(defaults):
        dialog.addChoice('Image_'+ str(index + 1), image_titles, image_titles[default])
    dialog.showDialog()
    if dialog.wasCanceled():
        return None
    return [dialog.getNextChoiceIndex() for _ in defaults]
Ejemplo n.º 31
0
def check_dependencies():
    installed_plugins = os.listdir(Menus.getPlugInsPath())
    for dependency, site in _dependencies.iteritems():
        if not any(dependency in x for x in installed_plugins):
            msg = GenericDialog("Missing dependency")
            msg.addMessage(
                "Missing dependency {}, \n go to {} for installation instructions. "
                .format(dependency, site))
            msg.showDialog()
            raise RuntimeError(
                "Missing dependency {}, \n go to {} for installation instructions. "
                .format(dependency, site))
def get_color(nChannel=n_Channel):
    color_strings = [
        "Green", "Magenta", "Cyan", "Blue", "Red", "Yellow", "Orange", "Gray",
        "Black"
    ]

    gd = GenericDialog("Set Colors")

    for i in range(nChannel):
        gd.addChoice("Channel {}".format(i + 1), color_strings,
                     color_strings[i])

    gd.showDialog()

    if gd.wasCanceled():
        return
    else:
        selected_colours = [gd.getNextChoice() for _ in range(nChannel)]
        return selected_colours
Ejemplo n.º 33
0
def getThresholds():
	thresholds = {}
	
	gd = GenericDialog("Threshold options")
	gd.addChoice("How would you like to set your thresholds?", ["default", "use threshold csv file"], "default")
	gd.showDialog()

	choice = gd.getNextChoice()
	log.write("Option: " + choice + "\n")

	if choice == "use threshold csv file":
		path = OpenDialog("Open the thresholds csv file")
		log.write("File used: " + path.getPath() + "\n")
		with open(path.getPath()) as csvfile:
			reader = csv.DictReader(csvfile)
			for row in reader:
				thresholds = row
	return thresholds
Ejemplo n.º 34
0
	def getOptionsDialog(self, imp):
		thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData",  "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"]
		gd = GenericDialog("Please select channels to collocalize")
		for i in range(1, imp.getNChannels() + 1):
			gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None")
		gd.showDialog()
		if gd.wasCanceled():
			self.exit()
		channels = []
		for i in range(1, imp.getNChannels() + 1):
			method = gd.getNextChoice()
			self.methods.append(method)
			if method != "None":
				channels.append(i)
		for x in channels:
			for y in channels:
				if x < y:
					self.pairs.append((x, y))
Ejemplo n.º 35
0
def getNames():
	names = {}
	
	gd = GenericDialog("Naming options")
	gd.addChoice("How would you like to name your results for each well?", ["default", "use name convention csv file"], "default")
	gd.showDialog()

	choice = gd.getNextChoice()

	log.write("Option: " + choice + "\n")

	if choice == "use name convention csv file":
		path = OpenDialog("Open the names csv file")
		log.write("File used: " + path.getPath() + "\n")
		
		with open(path.getPath()) as csvfile:
			reader = csv.DictReader(csvfile)
			for row in reader:
				names[row['Row']] = row 
	
	return names
Ejemplo n.º 36
0
def getNames():
    info = []

    gd = GenericDialog("Naming options")
    gd.addChoice("How would you like to output your results?",
                 ["default", "use information csv file"], "default")
    gd.showDialog()

    choice = gd.getNextChoice()

    log.write("Option: " + choice + "\n")

    if choice == "use information csv file":
        path = OpenDialog("Open the names csv file")
        log.write("File used: " + path.getPath() + "\n")

        with open(path.getPath()) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                info.append(row)

    return info
Ejemplo n.º 37
0
def getOptions(imp):
  gd = GenericDialog("Correct 3D Drift Options")
  channels = []
  for ch in range(1, imp.getNChannels()+1 ):
    channels.append(str(ch))
  gd.addMessage("Select a channel to be used for the registration.")
  gd.addChoice("     channel:", channels, channels[0])
  gd.addCheckbox("Use virtualstack?", False)
  gd.addMessage("This will store the registered hyperstack as an image sequence and\nshould be used if free RAM is less than 2X the size of the hyperstack. ")
  gd.showDialog()
  if gd.wasCanceled():
    return
  channel = gd.getNextChoiceIndex() + 1  # zero-based
  virtual = gd.getNextBoolean()
  return channel, virtual
        print "\nwill not analyze file:",filename
        continue
      else:
        #print root
        print "\nanalyzing file:",filename
        imp = Opener().openImage(root, filename)
        analyse(imp, root, filename, thresholds)

          
if __name__ == '__main__':
  srcDir = DirectoryChooser("Choose directory").getDirectory()
  #od = OpenDialog("Click on one of the image files in the folder to be analysed", None	)
  #filename = od.getFileName()
  #foldername = od.getDirectory()
  #foldername = "Z:/Tischi/projects/CellZome/2015-04-27--3D_Tissue/data"
  gd = GenericDialog("3D Tissue analysis");
  gd.addNumericField("Threshold Ch1: ", 30, 0);
  gd.addNumericField("Threshold Ch2: ", 30, 0);
  gd.addNumericField("Threshold Ch3: ", 30, 0);
  gd.showDialog();
  #if (gd.wasCanceled()):
  #  return
  thresholds = []
  thresholds.append(gd.getNextNumber())
  thresholds.append(gd.getNextNumber())
  thresholds.append(gd.getNextNumber())
  #foldername = "Z:/Tischi/projects/CellZome/2015-04-29--3D_Tissue/subset"
  
  if None != srcDir:
    print "\n\n\n\nfoldername = "+srcDir
    getFilesAndAnalyze(srcDir, thresholds)
def getOptions():
	global numberOfChannels
	global replaceExisting

	gd = GenericDialog("Options")
	gd.addNumericField("Number of channel", 2, 0) # show 0 decimals
	gd.addCheckbox("Replace Destination .tif files", 0)
	gd.addHelp("http://robertcudmore.org/software_index.html")
	gd.showDialog()

	if gd.wasCanceled():
		print "User cancelled dialog."
		return -1
	#read out options
	numberOfChannels = gd.getNextNumber()
	replaceExisting = gd.getNextBoolean()
	

	return 1 #int(numberOfChannels)
Ejemplo n.º 40
0
import re
import os
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ

dc = DirectoryChooser("Choose directory with image tiles you want to stitch...")
sourceDir = dc.getDirectory()

opener = OpenDialog("Select DMI metadata file...",sourceDir,"tile_info.txt")
metadata_file = opener.getPath()

gd = GenericDialog("Input image name...")
gd.addStringField("Image_prefix:","IMGid")
gd.addMessage("Input directory: " + sourceDir)
gd.showDialog()
img_name = gd.getNextString()
outputPath = sourceDir + img_name + "_seq"

if sourceDir is not None and metadata_file is not None:
	
	## computes tiling information from DMI metadata
	metadata = IJ.openAsString(metadata_file)
	p = re.compile(r'X Tiles: (\d+)')
	m = p.search(metadata)
	if m is None:
		xtiles = 0
	else:
		xtiles = int(m.group(1))
	p = re.compile(r'Y Tiles: (\d+)')
def make_directory(imgDir):
    """ Makes the necessary output directories or overwrites current ones. """
    if not path.exists(imgDir) or not path.isdir(imgDir):
        print "Not a valid directory"
        exit(0)

    if not path.exists(imgDir+"/binary"):
        mkdir(imgDir+"/binary")

    else:
    	gd = GenericDialog("Confirm Overwrite")
    	choices = ["Yes", "No"]
    	gd.addChoice("Overwrite \"binary\" folder?", choices, choices[0])
    	gd.showDialog()
    	if gd.wasCanceled():
    		exit(0)
    	choice = gd.getNextChoice()
    	if choice == "No":
    		exit(0)
    	shutil.rmtree(imgDir+"/binary")
    	mkdir(imgDir+"/binary")


    if not path.exists(imgDir+"/greyscale"):
        mkdir(imgDir+"/greyscale")

    else:
    	gd = GenericDialog("Confirm Overwrite")
    	choices = ["Yes", "No"]
    	gd.addChoice("Overwrite \"greyscale\" folder?", choices, choices[0])
    	gd.showDialog()
    	if gd.wasCanceled():
    		exit(0)
    	choice = gd.getNextChoice()
    	if choice == "No":
    		exit(0)
    	shutil.rmtree(imgDir+"/greyscale")
    	mkdir(imgDir+"/greyscale")
Ejemplo n.º 42
0
frame.addWindowListener( Closing() )
scoreField.requestFocusInWindow()

# Get the grid files
chooser = JFileChooser()
chooser.setDialogTitle("Choose plate grids")
chooser.setMultiSelectionEnabled(True)
chooser.setCurrentDirectory( File(os.path.expanduser("~")))
chooser.showOpenDialog(JPanel())

# This is a hack to get a file path from the
# sun.awt.shell.DefaultShellFolder object returned by the chooser
fp = [str(i) for i in chooser.getSelectedFiles()]

if len(fp) != 0:
    gd = GenericDialog("Name your output file")
    gd.addStringField("Score file name", "scores.csv")
    gd.showDialog()
    if not gd.wasCanceled():
        scoreFile = gd.getNextString()
        scoreFile = os.path.join( os.path.split(fp[0])[0], scoreFile)
        cropDir = os.path.splitext( scoreFile)[0] + "_cropped"
        # Initialize the grid readers
        plateGrid = GridSet(fp,scoreFile,cropDir)
        plateGrid.openNext()
        # Show the GUI
        frame.setVisible(True)
    else:
        pass
else:
    pass
Ejemplo n.º 43
0
def get_options():
    """Ask user for input values."""
    dlg = GenericDialog("Options for Boxed Heatmap")
    dlg.addMessage("Boxed Heatmap settings")
    dlg.addMessage("Specify box size:")
    dlg.addNumericField("Width", 32, 0)
    dlg.addNumericField("Height", 32, 0)
    dlg.showDialog()
    if dlg.wasCanceled():
        print "User canceled dialog."
        return  None
    # Read out the options
    boxw = int(dlg.getNextNumber())
    boxh = int(dlg.getNextNumber())
    return boxw, boxh
Ejemplo n.º 44
0
from ij.measure import Measurements
from ij.process import ImageProcessor
from ij.process import ImageConverter
from ij.gui import WaitForUserDialog
from ij.gui import GenericDialog
from ij.plugin.frame import RoiManager
from ij.plugin.filter import ParticleAnalyzer
from ij.plugin import ChannelSplitter


# Set Threshold mode

thresholdMode = False


gd = GenericDialog("Set Threshold Mode")
gd.addChoice("Would you like to enable thresholding mode?", ["No, run the normal macro", "Yes, enable thresholding mode"], "No")
gd.showDialog()
if gd.getNextChoice() == "Yes, enable thresholding mode":
	thresholdMode = True

gd = GenericDialog("Set Thresholds")
gd.addStringField("Lower bound for Red", "90")
gd.addStringField("Lower bound for Green", "90")
gd.addStringField("Lower bound for Blue", "100")
gd.showDialog()


thresholds = {}
thresholds["Red"] = int(gd.getNextString()
)
Ejemplo n.º 45
0
def get_setup():
    '''Returns two ImagePlus objects and a dictionary of properties to copy.'''
    dialog = GenericDialog('Copy Properties setup')
    dialog.addMessage('Select the source and target image and the properties to copy.')
    image_ids = WindowManager.getIDList()
    if not image_ids or len(image_ids) < 2:
        IJ.showMessage('Two or more images are necessary to use this plugin.')
        return [None]*3
    image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids]
    dialog.addChoice('Source', image_titles, image_titles[0])
    dialog.addChoice('Target', image_titles, image_titles[1])
    dialog.addCheckbox('Copy Calibration', True)
    dialog.addCheckbox('Copy Slice Labels', False)
    dialog.showDialog()
    if dialog.wasCanceled():
        return [None]*3
    source = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    target = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    choices = {'cal': dialog.getNextBoolean(),
               'labels': dialog.getNextBoolean()
              }
    return source, target, choices
Ejemplo n.º 46
0
def pause_for_debug():
    gd = GenericDialog("Continue?")
    gd.showDialog()
    if gd.wasCanceled():
        raise Exception("Run interupted")
Ejemplo n.º 47
0
def Options(sourceFolder):
	#globals
	global gFileType
	global gGetNumChanFromScanImage
	global gNumChannels
		
	global gDoAlign
	global gAlignThisChannel
	
	global gDoCrop
	global gCropLeft
	global gCropTop
	global gCropWidth
	global gCropHeight
	
	global gAlignOnMiddleSlice
	global gAlignOnThisSlice
	global gRemoveCalibration
	global gLinearShift
	global gSave8bit

	tifNames = [file.name for file in File(sourceFolder).listFiles(Filter())]
	lsmNames = [file.name for file in File(sourceFolder).listFiles(Filter_LSM())]
	
	numTifs = len(tifNames)
	numLSM = len(lsmNames)

	gd = GenericDialog('Align Batch 7 Options')
	#gd.addStringField('Command: ', '')

	gd.addMessage('Source Folder: ' + sourceFolder)
	gd.addMessage('Number of .tif files: ' + str(numTifs))
	gd.addMessage('Number of .lsm files: ' + str(numLSM))
	
	gd.addChoice('File Type', ['tif','lsm'], gFileType)
	
	#gd.setInsets(5,0,3)
	#0
	gd.addCheckboxGroup(1, 1, ['Get Number Of Channels From ScanImage 3.x or 4.x header'], [gGetNumChanFromScanImage], ['Channels'])
	gd.addNumericField('Otherwise, Assume All Stacks Have This Number Of Channels: ', gNumChannels, 0)

	print gLinearShift
	
	#1
	gd.addCheckboxGroup(1, 1, ['Remove Linear Calibration From ScanImage 4.x'], [gRemoveCalibration], ['ScanImage4'])
	gd.addNumericField('And offset (subtract) by this amount: ', gLinearShift, 0)
	gd.addMessage('20151110, this number = 2^15-512 = 32768-512 = 32256')
	
	#2
	gd.addCheckboxGroup(1, 1, ['Crop All Images (pixels)'], [gDoCrop], ['Crop'])
	gd.addNumericField('Left', gCropLeft, 0)
	gd.addNumericField('Top', gCropTop, 0)
	gd.addNumericField('Width', gCropWidth, 0)
	gd.addNumericField('Height', gCropHeight, 0)

	#gd.setInsets(5,0,3)
	#3
	gd.addCheckboxGroup(1, 1, ['Run MultiStackReg'], [gDoAlign], ['MultStackReg'])
	gd.addNumericField('If 2 Channels Then Align On This Channel', gAlignThisChannel, 0)
	
	#4
	gd.addCheckboxGroup(1, 1, ['Start Alignment On Middle Slice'], [gAlignOnMiddleSlice], ['Align On Middle Slice'])
	gd.addNumericField('Otherwise, Start Alignment On This Slice', gAlignOnThisSlice, 0)

	#5
	gd.addCheckboxGroup(1, 1, ['Save 8-bit'], [gSave8bit], ['Save 8-bit (at end)'])
	#gd.addCheckbox('Save 8-bit', gSave8bit)
	
	gd.showDialog()

	if gd.wasCanceled():
		print 'Options Was Cancelled by user'
		return 0
	else:
		print 'Reading values'
		gFileType = gd.getNextChoice()
		
		gNumChannels = int(gd.getNextNumber())

		gLinearShift = int(gd.getNextNumber())

		gCropLeft = int(gd.getNextNumber())
		gCropTop = int(gd.getNextNumber())
		gCropWidth = int(gd.getNextNumber())
		gCropHeight = int(gd.getNextNumber())

		gAlignThisChannel = int(gd.getNextNumber())
		gAlignOnThisSlice = int(gd.getNextNumber())

		checks = gd.getCheckboxes()
		checkIdx = 0
		for check in checks:
			#print check.getState()
			if checkIdx==0:
				gGetNumChanFromScanImage = check.getState()
			if checkIdx==1:
				gRemoveCalibration = check.getState()
			if checkIdx==2:
				gDoCrop = check.getState()
			if checkIdx==3:
				gDoAlign = check.getState()
			if checkIdx==4:
				gAlignOnMiddleSlice = check.getState()

			if checkIdx==5:
				gSave8bit = check.getState()
			checkIdx += 1

		# print to fiji console
		bPrintLog('These are your global options:', 0)
		bPrintLog('gFileType=' + gFileType, 1)
		bPrintLog('gGetNumChanFromScanImage=' + str(gGetNumChanFromScanImage), 1)
		bPrintLog('gNumChannels=' + str(gNumChannels), 1)
		bPrintLog('gRemoveCalibration=' + str(gRemoveCalibration), 1)
		bPrintLog('gLinearShift=' + str(gLinearShift), 1)
		bPrintLog('gDoCrop=' + str(gDoCrop), 1)
		bPrintLog('gDoAlign=' + str(gDoAlign), 1)
		bPrintLog('gAlignThisChannel=' + str(gAlignThisChannel), 1)
		bPrintLog('gSave8bit=' + str(gSave8bit), 1)
		
		return 1
Ejemplo n.º 48
0
def run(title):
    gd = GenericDialog("Record Window")
    gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.")
    gd.addNumericField("Max. frames:", 50, 0)
    gd.addNumericField("Milisecond interval:", 300, 0)
    gd.addSlider("Start in (seconds):", 0, 20, 5)
    frames = []
    titles = []
    for f in Frame.getFrames():
        if f.isEnabled() and f.isVisible():
            frames.append(f)
            titles.append(f.getTitle())
    gd.addChoice("Window:", titles, titles[0])
    gd.addCheckbox("To file", False)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    frame = frames[gd.getNextChoiceIndex()]
    delay = int(gd.getNextNumber())
    tofile = gd.getNextBoolean()

    dir = None
    if tofile:
        dc = DirectoryChooser("Directory to store image frames")
        dir = dc.getDirectory()
        if dir is None:
            return  # dialog canceled

    snaps = []
    borders = None
    executors = Executors.newFixedThreadPool(1)
    try:
        while delay > 0:
            IJ.showStatus("Starting in " + str(delay) + "s.")
            time.sleep(1)  # one second
            delay -= 1

        IJ.showStatus("Capturing frame borders...")
        bounds = frame.getBounds()
        robot = Robot()
        frame.toFront()
        time.sleep(0.5)  # half a second
        borders = robot.createScreenCapture(bounds)

        IJ.showStatus("Recording " + frame.getTitle())

        # Set box to the inside borders of the frame
        insets = frame.getInsets()
        box = bounds.clone()
        box.x = insets.left
        box.y = insets.top
        box.width -= insets.left + insets.right
        box.height -= insets.top + insets.bottom

        start = System.currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        i = 1
        fus = None
        if tofile:
            fus = []

            # 0 n_frames means continuous acquisition
        while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval):
            now = System.currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                img = snapshot(frame, box)
                if tofile:
                    fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets)))  # will flush img
                    i += 1
                else:
                    snaps.append(img)
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)
                # interrupt capturing:
            if IJ.escapePressed():
                IJ.showStatus("Recording user-interrupted")
                break

                # debug:
                # print "insets:", insets
                # print "bounds:", bounds
                # print "box:", box
                # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight()

                # Create stack
        stack = None
        if tofile:
            for fu in snaps:
                fu.get()  # wait on all
            stack = VirtualStack(bounds.width, bounds.height, None, dir)
            files = File(dir).list(TifFilter())
            Arrays.sort(files)
            for f in files:
                stack.addSlice(f)
        else:
            stack = ImageStack(bounds.width, bounds.height, None)
            t = 0
            for snap, real_interval in zip(snaps, intervals):
                bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB)
                g = bi.createGraphics()
                g.drawImage(borders, 0, 0, None)
                g.drawImage(snap, insets.left, insets.top, None)
                stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor())
                t += real_interval
                snap.flush()
                bi.flush()

        borders.flush()

        ImagePlus(frame.getTitle() + " recording", stack).show()
        IJ.showStatus("Done recording " + frame.getTitle())
    except Exception, e:
        print "Some error ocurred:"
        print e.printStackTrace()
        IJ.showStatus("")
        if borders is not None:
            borders.flush()
        for snap in snaps:
            snap.flush()
Ejemplo n.º 49
0
	return values

dc = DirectoryChooser("Choose directory with OME.TIF files...")
sourceDir = dc.getDirectory()

if not(sourceDir is None):
	if not os.path.exists(sourceDir + "resized"):
		os.mkdir(sourceDir + "resized")

	dirSize = get_directory_size(sourceDir)
	dirSizeMB = dirSize / 1048576
	memoryObj = Memory()
	memFiji = memoryObj.maxMemory()
	memFijiMB = memFiji / 1048576

	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Sizing_ratio (Final disk space / Initial disk space):",0.25,2)
	gd.addMessage("Directory size: " + str(dirSizeMB) + "MB")
	gd.addMessage("Maximum memory: " + str(memFijiMB) + "MB")
	mem_recs = calculate_memory_recs(dirSize,memFiji)
	print mem_recs
	for i in range(0,len(mem_recs)):
		ratio_rec = float(mem_recs[i]) / dirSizeMB
		if (ratio_rec > 1):
			ratio_rec = 1
		print ratio_rec
		ratio_rec_str = "%.3f" % ratio_rec
		gd.addMessage(str(i+1)+"-channel: " + str(mem_recs[i]) + "MB; Ratio: " + ratio_rec_str)
	gd.showDialog()
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
Ejemplo n.º 50
0
from java.net import URI

desktop = Desktop.getDesktop()
uri = URI("https://colab.research.google.com/drive/1PRgFZnd0OtT6p61Ce2y0POEoKPNtTE5N#scrollTo=uU-B_7MwFohd") #test url
desktop.browse(uri)


session = None
channel = None

DIALOG = True

if (DIALOG):
	# ----------------- DIALOG TO FILL GLOBAL PARAMETERS -----

	gui = GenericDialog("Parameters")
	gui.addStringField("NGROK Server address :", "0.tcp.ngrok.io")
	gui.addStringField("PORT :", "")
	gui.showDialog()
	HOST = gui.getNextString()
	PORT = int(gui.getNextString())

	gui = GenericDialogPlus("Parameters")
	gui.addFileField("Select a model file in Keras format (*.h5) : ", "")
	gui.showDialog()
	if gui.wasOKed():
	    LOCAL_MODEL_FILENAME   = gui.getNextString()

	gui = GenericDialogPlus("Parameters")
	gui.addFileField("Select a python script file to upload on the server (*.py)  : ", "")
	gui.showDialog()
def getOptions(imp):
  gd = GenericDialog("Correct 3D Drift Options")
  channels = []
  for ch in range(1, imp.getNChannels()+1 ):
    channels.append(str(ch))
  gd.addChoice("Channel for registration:", channels, channels[0])
  gd.addCheckbox("Multi_time_scale computation for enhanced detection of slow drifts?", False)
  gd.addCheckbox("Sub_pixel drift correction (possibly needed for slow drifts)?", False)
  gd.addCheckbox("Edge_enhance images for possibly improved drift detection?", False)
  gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False)
  gd.addCheckbox("Only compute drift vectors?", False)
  gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.")
  gd.showDialog()
  if gd.wasCanceled():
    return
  channel = gd.getNextChoiceIndex() + 1  # zero-based
  multi_time_scale = gd.getNextBoolean()
  subpixel = gd.getNextBoolean()
  process = gd.getNextBoolean()
  virtual = gd.getNextBoolean()
  only_compute = gd.getNextBoolean()
  return channel, virtual, multi_time_scale, subpixel, process, only_compute
Ejemplo n.º 52
0
def run():
	types = ['oneDay','oneMouse','oneFile','oneMonth','OneFolder','mapManager']

	gd = GenericDialog('Define Source Options')
	#gd.addMessage('Choose the Source type:')
	gd.addChoice('Source Type:',types,types[0])
	gd.showDialog()



	if gd.wasCanceled():
		bPrintLog('user cancel the plugin',1)
		return 0
	else:
		srcType = gd.getNextChoiceIndex()
		#run one day
		if srcType == 0:
			dayFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory()
			if not os.path.isdir(dayFolder):
				bPrintLog('\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n',0)
				return 0

			overWriteDate(dayFolder)
		
		#run one mouse
		if srcType == 1:
			mouseFolder = DirectoryChooser('Please Choose A Mouse Directory Of .tif Files').getDirectory()
			if not mouseFolder:
				exit(1)
			overWriteMouse(mouseFolder)

		#run one file
		if srcType == 2:
			od = OpenDialog("Choose a convoluted tif file to overwrite", None)
			srcDirectory = od.getDirectory()
			srcFile = od.getFileName()
			if srcFile != None:
				fileFullPath = os.path.join(srcDirectory,srcFile)
				convert32to16(fileFullPath)
		#run one month
		if srcType == 3:
			monthFolder = DirectoryChooser('Please Choose A MONTH Directory Of .tif Files').getDirectory()
			if not os.path.isdir(monthFolder):
				bPrintLog('\nERROR: runOneMonth() did not find folder: ' + monthFolder + '\n',0)
				return 0

			runOneMonth(monthFolder)

		#run one Folder
		if srcType == 4:
			srcFolder = DirectoryChooser('Please Choose A folder Of .tif Files').getDirectory()
			if not os.path.isdir(srcFolder):
				bPrintLog('\nERROR: runOneFolder() did not find folder: ' + srcFolder + '\n',0)
				return 0

			runOneFolder(srcFolder)
		if srcType == 5:	#align centain map's raw folder
			mapPath = 'G:/ZY/MapManager3'
			#mapNames = raw_input('type maps initials seperated with ,: ').split(',')	#raw_input does not work here
			#mapNames = tuple(mapNames)
			mapNames = "F58,F59"	#preset
			#get map names
			gd = GenericDialog('Choose maps for alignment')
			gd.addStringField("maps root path",mapPath,50)
			gd.addStringField("maps name initials sep = ','(empty for all)",mapNames,50)
			gd.showDialog()
			if gd.wasCanceled():
				bPrintLog('user cancel the plugin',0)
				return 0
			mapPath = gd.getNextString()
			mapNames = tuple(gd.getNextString().split(','))
			mapFolders = [f for f in os.listdir(mapPath) if f.startswith(mapNames) and os.path.isdir(os.path.join(mapPath,f))]

			if len(mapFolders) == 0:
				bPrintLog('\nERROR: no map folder found',0)
				return 0
			
 			bPrintLog('Map Folder number: ' + str(len(mapFolders)),0)
        	#put option here so we do not have to click for each folder
			sourceFolders= [mapPath + '/' + mapFolder + '/raw/raw_userRaw' for mapFolder in mapFolders]
			for srcFolder in sourceFolders:
				runOneFolder(srcFolder)
Ejemplo n.º 53
0
def open_Octopus_file():

	# set up a file info structure
	fi = FileInfo()
	fi.fileFormat = fi.RAW
	fi.fileType=FileInfo.GRAY16_UNSIGNED
	fi.intelByteOrder = True
	fi.nImages = 1

	op = OpenDialog("Choose Octopus .dth file...", "")
	if not op.getDirectory(): return False

	# get the file extension
	file_extension = re.search('(\.[a-z][a-z][a-z])', op.getFileName()).group(1)
	
	if file_extension != ".dth":
		dlg = GenericDialog("Warning")
		dlg.addMessage("Please select an octopus .dth file")
		dlg.showDialog()
		return False

	# now strip the filename into a stem and index
	file_parse = re.match('([a-zA-z0-9_]*_)([0-9]+)\.dth', op.getFileName())
	file_stem = file_parse.group(1)
	file_index = int( file_parse.group(2) )

	# ok now we need to parse the header info
	header = get_Octopus_header(op.getDirectory(), file_stem, file_index)
	fi.nImages  = len(header['N'])

	# check to see whether we have a bit depth, if not, assume 16-bit
	if 'Bit_Depth' in header:
		print header['Bit_Depth']
		bit_depth = int(header['Bit_Depth'][0])
		if bit_depth == 8: fi.fileType = FileInfo.GRAY8
	else:
		bit_depth = 16

	# will assume that all files have the same size
	fi.width = int( header['W'][0] )
	fi.height = int( header['H'][0] )
	file_timestamp = strftime("%a, %d %b %Y %H:%M:%S", gmtime(float(header['Time'][0])) )
	

	# make a new imagestack to store the data
	stack = ImageStack(fi.width, fi.height)

	# finally, we need to make a list of files to import as sometimes we have
	# non contiguous file numbers
	try:
		files = os.listdir(op.getDirectory())
	except IOError:
		raise IOError( "No files exist in directory: " + op.getDirectory())

	filenums = []
	for f in files:
		# strip off the stem, and get the number
		targetfile = re.match(file_stem+'([0-9]+)\.dth', f)
		# only take thosefiles which match the formatting requirements
		if targetfile:
			filenums.append( int(targetfile.group(1)) )

	# sort the file numbers
	sorted_filenums = sorted(filenums)

	# make a file stats string
	file_stats_str = file_stem + '\n' + str(fi.width) +'x' + str(fi.height) + 'x' + \
		str(len(sorted_filenums)) +' ('+str(bit_depth)+'-bit)\n' + file_timestamp


	# now open a dialog to let the user set options
	dlg = GenericDialog("Load Octopus Stream (v"+__version__+")")
	dlg.addMessage(file_stats_str)
	dlg.addStringField("Title: ", file_stem)
	dlg.addNumericField("Start: ", 1, 0);
	dlg.addNumericField("End: ", len(sorted_filenums), 0)
	dlg.addCheckbox("Open headers", True)
	dlg.addCheckbox("Contiguous stream?", False)
	dlg.addCheckbox("8-bit unsigned", bit_depth==8)
	dlg.showDialog()

	# if we cancel the dialog, exit here
	if dlg.wasCanceled():
		return

	# set some params
	file_title = dlg.getNextString()
	file_start = dlg.getNextNumber()
	file_end = dlg.getNextNumber()
	DISPLAY_HEADER = bool( dlg.getNextBoolean() )

	# check the ranges
	if file_start > file_end: 
		file_start, file_end = file_end, file_start
	if file_start < 1: 
		file_start = 1
	if file_end > len(sorted_filenums): 
		file_end = len(sorted_filenums) 

	# now set these to the actual file numbers in the stream
	file_start = sorted_filenums[int(file_start)-1]
	file_end = sorted_filenums[int(file_end)-1]

	files_to_open = [n for n in sorted_filenums if n>=file_start and n<=file_end]

	# if we've got too many, truncate the list
	if (len(files_to_open) * fi.nImages * fi.width * fi.height) > (MAX_FRAMES_TO_IMPORT*512*512):
		dlg = GenericDialog("Warning")
		dlg.addMessage("This may use a lot of memory. Continue?")
		dlg.showDialog()
		if dlg.wasCanceled(): return False

	IJ.log( "Opening file: " + op.getDirectory() + op.getFileName() )
	IJ.log( file_stats_str + "\nFile range: " + str(files_to_open[0]) + \
		"-" + str(files_to_open[-1]) +"\n" )

	# make a results table for the metadata
	# NOTE: horrible looping at the moment, but works
	if DISPLAY_HEADER:
		rt = ResultsTable()

	# ok now we can put the files together into the stack
	for i in files_to_open:

		# open the original .dat file and get the stack
		fi.fileName = get_Octopus_filename( op.getDirectory(), file_stem, i)
		
		if os.path.isfile( fi.fileName ):
			fo = FileOpener(fi)
			imp = fo.open(False).getStack() 
	
			# put the slices into the stack
			for im_slice in xrange( imp.getSize() ):
				ip = imp.getProcessor( im_slice+1 )
				if bit_depth == 8:
					bi = ip.getBufferedImage()
				else:
					bi = ip.get16BitBufferedImage() 
				stack.addSlice( file_title,  ip )


			if DISPLAY_HEADER:
				header = get_Octopus_header(op.getDirectory(), file_stem, i)
				for n in xrange(len(header['N'])):
					rt.incrementCounter()
					for k in header.keys():
						rt.addValue(k, parse_header( header[k][n] ) )

		else:
			break

	# done!
	output = ImagePlus('Octopus ('+file_stem+')', stack)
	output.show()

	if DISPLAY_HEADER:
		rt.show("Octopus header metadata")

	return True
Ejemplo n.º 54
0
def get_setup():
    ''' Returns the drift correction mode and two image.'''
    options = drift.get_options()
    modes = drift.get_modes()
    dialog = GenericDialog('Jump-ratio setup')
    dialog.addMessage('Select the mode  for drift correction\n' +
                      'and the images to process.')
    dialog.addChoice('Mode:', options, options[0])
    image_ids = WindowManager.getIDList()
    if not image_ids or len(image_ids) < 2:
        return [None]*3
    image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids]
    dialog.addMessage('Post-edge is divided by the pre-edge.')
    dialog.addChoice('Pre-edge', image_titles, image_titles[0])
    dialog.addChoice('Post-edge', image_titles, image_titles[1])
    dialog.showDialog()
    if dialog.wasCanceled():
        return [None]*3
    mode = modes[dialog.getNextChoiceIndex()]
    img1 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    img2 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    return mode, img1, img2
from ij import IJ
from ij.gui import GenericDialog

gd = GenericDialog("Cells segmentation parameters");
gd.addNumericField("Radius for Local Thresholding", 30.0, 0);
gd.addNumericField("Size minimum for particles", 50.0, 0);
gd.addNumericField("Circularity minimum value", 0.60, 2);
gd.showDialog();

values = gd.getNumericFields();
for val in values:
	IJ.log(val.text)
from ij import WindowManager

# Gets the input LSM image
theOpenDialog = OpenDialog("Choose large LSM file to open...")
theFilePath = theOpenDialog.getPath()
if not(theFilePath is None):
	theDirectory = theOpenDialog.getDirectory()
	theFileName = theOpenDialog.getFileName()
	baseName = os.path.splitext(theFileName)[0]
		
	# Creates the output directory
	if not os.path.exists(theDirectory + baseName + "_resized"):
		os.mkdir(theDirectory + baseName + "_resized")

	# Asks for parameters
	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Start tile:",1,0)
	gd.addNumericField("Finish tile:",9,0)
	gd.addNumericField("Final disk space / Initial disk space:",0.25,2)
	gd.addNumericField("Step size (higher is faster but uses more memory):",10,0)
	gd.showDialog()
	startTile = int(gd.getNextNumber())
	finishTile = int(gd.getNextNumber())
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
	stepSize = int(gd.getNextNumber())
	
	# Performs scaling
	if (gd.wasOKed()):
		anchorTiles = range(startTile,finishTile+1,stepSize)
		print anchorTiles
Ejemplo n.º 57
0
from ij.gui import GenericDialog

import sys
from java.lang.System import getProperty
sys.path.append(getProperty("fiji.dir") + "/plugins/CMTK_Registration")

gd = GenericDialog('About CMTK')
gd.addMessage('CMTK Registration suite is open source software released under GPLv3',)
gd.addMessage('Currently installed CMTK version: '+cmtkgui.installed_version())
gd.addMessage('CMTK binary directory: '+cmtkgui.bin_dir())
gd.setCancelLabel("CMTK Web Page")
gd.showDialog()
if gd.wasCanceled():
	from ij import IJ
	IJ.runPlugIn("ij.plugin.BrowserLauncher", "http://www.nitrc.org/projects/cmtk/")
dc = DirectoryChooser("Choose an input directory")
inputDirectory = dc.getDirectory()

dc = DirectoryChooser("Select an output directory")
outputDirectory = dc.getDirectory()

for image in os.listdir(inputDirectory):
    print(image)
    if "stack" in image:
        imp = IJ.openImage(inputDirectory + "/" + image)
        imp2 = IJ.openImage(inputDirectory + "/" +
                            image.replace("stack", "montage"))
        imp.show()
        imp2.show()

        gd = GenericDialog("?")
        gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No")
        gd.showDialog()
        if gd.getNextChoice() == "Yes":
            imp2.close()
            IJ.run("Brightness/Contrast...")
            WaitForUserDialog("Title", "Adjust intensities").show()
            IJ.run("Stack to Images", "")
            IJ.run(imp, "Merge Channels...",
                   "c2=Green c3=Blue c6=Magenta c7=Yellow create keep")
            imp = WindowManager.getCurrentImage()
            IJ.run(imp, "RGB Color", "")
            IJ.run(imp, "Images to Stack", "name=Stack title=[] use")
            #WaitForUserDialog("Title", "Now you should have a stack check it out ").show()
            imp = WindowManager.getCurrentImage()  # the Stack
Ejemplo n.º 59
0
import re
import os
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ

dc = DirectoryChooser("Choose directory with image tiles you want to stitch...")
sourceDir = dc.getDirectory()

opener = OpenDialog("Select DMI metadata file...",sourceDir,"tile_info.txt")
metadata_file = opener.getPath()

gd = GenericDialog("Input image name...")
gd.addStringField("Name your image (write a prefix):","IMGid")
gd.addMessage("Input directory: " + sourceDir)
gd.showDialog()
img_name = gd.getNextString()
outputPath = sourceDir + img_name + "_seq"

if sourceDir is not None and metadata_file is not None:
	
	## computes tiling information from DMI metadata
	metadata = IJ.openAsString(metadata_file)
	p = re.compile(r'X Tiles: (\d+)')
	m = p.search(metadata)
	if m is None:
		xtiles = 0
	else:
		xtiles = int(m.group(1))
	p = re.compile(r'Y Tiles: (\d+)')