def get_setup():
    ''' Returns the drift correction mode and three image.
    The order of return values is drift detection mode, pre-edge 1, pre-edge 2, post-edge.
    '''
    options = drift.get_options()
    modes = drift.get_modes()
    dialog = GenericDialog('3-window-method 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]*4
    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 1', image_titles, image_titles[0])
    dialog.addChoice('Pre-edge 2', image_titles, image_titles[1])
    dialog.addChoice('Post-edge', image_titles, image_titles[2])
    dialog.showDialog()
    if dialog.wasCanceled():
        return [None]*4
    mode = modes[dialog.getNextChoiceIndex()]
    img1 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    img2 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    img3 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()])
    return mode, img1, img2, img3
Пример #2
0
def main():
    properties = ImageProperties(imp)
    # Create a GenericDialog to configure renaming:
    gd = GenericDialog('Gatan Reamer')
    gd.addMessage('Modifying: %s' % (imp.getTitle(),))
    gd.addMessage('Recorded: %s' % (properties.date.toString(),))
    gd.addNumericField('Exposure time', properties.exposure, 4, field_width, 's')
    gd.addNumericField('Magnification:', properties.magnification, 0, field_width, 'x')
    mag_units = ('kx', 'x')
    gd.addChoice('Magnification unit:', mag_units, mag_units[0])
    gd.addMessage('The actual magnification is %.2f times larger.' % (properties.mag_factor,))
    gd.addCheckbox('Use actual magnification:', False)
    gd.addMessage('')
    gd.addNumericField('Energy loss:', properties.energyloss, 1, field_width, 'eV')
    gd.addStringField('Date:', properties.date_string, field_width)
    gd.addStringField('original name:', properties.name, field_width_long)
    gd.addStringField('Filename format', default_format_str, field_width_long)
    gd.showDialog()

    if not gd.wasCanceled():
        # Edit the properties to consiter user choices:
        properties.exposure = gd.getNextNumber()
        mag = gd.getNextNumber()
        properties.mag_unit = gd.getNextChoice()
        if gd.getNextBoolean():
            properties.calc_mag(mag)
        properties.energyloss = gd.getNextNumber()
        properties.date_string = gd.getNextString()
        properties.name = gd.getNextString()
        format_str = gd.getNextString()
        # Chenge the title:
        imp.setTitle(format_str % properties.to_dict())
Пример #3
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 getOptions(imp):
  gd = GenericDialog("Correct 3D Drift Options")
  channels = []
  for ch in range(1, imp.getNChannels()+1 ):
    channels.append(str(ch))
  methods = ["phase_correlation","center_of_mass"]
  gd.addChoice("Channel for registration:", channels, channels[0])
  gd.addChoice("Method for registration:", methods, methods[1])
  gd.addNumericField("Background value:", 0, 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("Drift correct only data inside ROI?", 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.addSlider("z_min of ROI", 1, imp.getNSlices(), 1)
  gd.addSlider("z_max of ROI", 1, imp.getNSlices(), imp.getNSlices())
  gd.showDialog()
  if gd.wasCanceled():
    return
  channel = gd.getNextChoiceIndex() + 1  # zero-based
  method = gd.getNextChoiceIndex() + 1  # zero-based
  bg_value = gd.getNextNumber()
  multi_time_scale = gd.getNextBoolean()
  subpixel = gd.getNextBoolean()
  process = gd.getNextBoolean()
  virtual = gd.getNextBoolean()
  only_roi = gd.getNextBoolean()
  only_compute = gd.getNextBoolean()
  roi_z_min = int(gd.getNextNumber())
  roi_z_max = int(gd.getNextNumber())
  return channel, method, bg_value, virtual, multi_time_scale, subpixel, process, only_roi, only_compute, roi_z_min, roi_z_max
Пример #5
0
def getOptions():
    lowerThreshold = 80;
    upperThreshold = 255;
    stepNumber = 1
    stepThreshold = 5;
    #p3DOCThreshold = 70;
    #p3DOCSlice = 1;
    p3DOCmin = 100;
    p3DOCmax = 2658480;
    gd = GenericDialog( "Parameters" )
    gd.addMessage("Binary mask thresholds")
    gd.addNumericField("Lower Threshold", lowerThreshold, 0)  # show 2 decimals  
    gd.addNumericField("Upper threshold", upperThreshold, 0)  # show 2 decimals  
    gd.addNumericField("Step number", stepNumber, 0)  # show 2 decimals  
    gd.addNumericField("Step threshold", stepThreshold, 0)  # show 2 decimals      
    gd.addMessage("3D Object Counter parameters")
    #gd.addNumericField("threshold", p3DOCThreshold, 0)  # show 2 decimals  
    gd.addNumericField("min.", p3DOCmin, 0)  # show 2 decimals  
    gd.addNumericField("max.", p3DOCmax, 0)  # show 2 decimals  
    gd.showDialog()  
    if gd.wasCanceled():  
        return  
    # Read out the options  
    lowerThreshold = gd.getNextNumber()
    upperThreshold = gd.getNextNumber()
    stepNumber = gd.getNextNumber()
    stepThreshold = gd.getNextNumber()
    #p3DOCThreshold = gd.getNextNumber()
    p3DOCmin = gd.getNextNumber()
    p3DOCmax = gd.getNextNumber()   
    return lowerThreshold, upperThreshold, stepNumber, stepThreshold, p3DOCmin, p3DOCmax      
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()
Пример #7
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 _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
Пример #9
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 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 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]
Пример #12
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
Пример #13
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]
Пример #14
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
Пример #15
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
Пример #16
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
Пример #17
0
def getOptions():  
    gd = GenericDialog("Options") 
    gd.addMessage("Filter Parameters")  
    gd.addNumericField("Smoothing Parameter", 0.1, 2)  # show 2 decimals
    gd.addNumericField("Patch radius", 2 , 1)
    gd.addNumericField("Search volume radius", 3 , 1)  
    gd.showDialog()  
    
    if gd.wasCanceled():  
        print "User canceled dialog!"  
        sys.exit()  
    # Read out the options    
    beta = gd.getNextNumber()
    patchradius = gd.getNextNumber()
    searchradius = gd.getNextNumber()     
    return beta, patchradius, searchradius  
Пример #18
0
def getOptions(options, image):
	if 'channel' not in options:
		channels = []
		for ch in range(1, image.getNChannels() + 1):
			channels.append("Channel " + "%i" % ch)
		dialog = GenericDialog("Select deconvolution parameters")
		dialog.addChoice("Channel to process", channels, None)
		dialog.addNumericField("Regularization parameter", 0.01, 2)
		dialog.addNumericField("Number of iterations", 50, 0)
		dialog.showDialog()
		if dialog.wasCanceled():
			sys.exit(1)	
		options['channel'] = dialog.getNextChoiceIndex()
		options['regparam'] = dialog.getNextNumber()
		options['iterations'] = dialog.getNextNumber()
	
	return options
Пример #19
0
def getRefIdDialog():  
  gd = GenericDialog("Reference Image")
  gd.addMessage("Preparing Turboreg(Rigidbody)\nSpecify image for reference")
  gd.addNumericField("Channel (C):", 2, 0)
  gd.addNumericField("Slice (Z):", 1, 0)
  gd.addNumericField("Frame (T):", 1, 0)
  gd.addMessage("Note: All fields start with 1 (not 0)")
  gd.showDialog()
  #  
  if gd.wasCanceled():
    print "User canceled dialog!"  
    return
  # Read out the options  
  c = int(gd.getNextNumber())
  z = int(gd.getNextNumber())
  t = int(gd.getNextNumber())
  refId = [c,z,t]
  return refId
def get_parameters(p, num_data_sets):
  gd = GenericDialog("Correct 3D Drift Options")

  gd.addMessage("Found "+str(num_data_sets)+" data sets")
  gd.addStringField("analyse", "all");

  gd.addMessage("Image analysis parameters:")
  for k in p.keys():
    gd.addNumericField(k, p[k], 2);
  gd.showDialog()
  if gd.wasCanceled():
    return

  to_be_analyzed = gd.getNextString()
  for k in p.keys():
    p[k] = gd.getNextNumber()
    
  return to_be_analyzed, p
Пример #21
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))
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)
#
def get_parameters(p, keys, num_data_sets):
  gd = GenericDialog("Please enter parameters")

  gd.addMessage("Found "+str(num_data_sets)+" data sets")
  gd.addStringField("analyse", "all");

  gd.addMessage("Image analysis parameters:")
  gd.addMessage("Please note: the threshold values are inclusive!\nThus, to exlude pixels with value 255 the upper threshold needs to be 254")
  
  
  for k in keys:
    gd.addNumericField(k, p[k], 2);
  gd.showDialog()
  if gd.wasCanceled():
    return

  to_be_analyzed = gd.getNextString()
  for k in keys:
    p[k] = gd.getNextNumber()
    
Пример #24
0
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.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()
  dt = gd.getNextNumber()
  return channel, virtual, multi_time_scale, subpixel, process
Пример #25
0
def run():
	bPrintLog(' ', 0)
	bPrintLog('=====================================', 0)
	bPrintLog('Running bAlign_Batch_v7', 0)
	bPrintLog('=====================================', 0)

	if len(sys.argv) < 2:
		print "   We need a hard-drive folder with .tif stacks as input"
		print "	  Usage: ./fiji-macosx bALign_Batch_7 <full-path-to-folder>/"
		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return 0
		strippedFolder = sourceFolder.replace(' ', '')
		if sourceFolder != strippedFolder:
			print 'found a space in specified path. Pease remove spaces and try again.'
			print 'path:', sourceFolder
			errorDialog = GenericDialog('Align Batch 7 Options')
			errorDialog.addMessage('bAlignBatch7 Error !!!')
			errorDialog.addMessage('There can not be any spaces in the path.')
			errorDialog.addMessage('Please remove spaces and try again.')
			errorDialog.addMessage('Offending path is:')
			errorDialog.addMessage(sourceFolder)
			errorDialog.showDialog()
			return 0
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'
	
	if not os.path.isdir(sourceFolder):
		bPrintLog('\nERROR: run() did not find folder: ' + sourceFolder + '\n',0)
		return 0

	
	if (Options(sourceFolder)):
		runOneFolder(sourceFolder)

	bPrintLog('=====================================', 0)
	bPrintLog('Done bAlign_Batch_v7', 0)
	bPrintLog('=====================================', 0)
        bPrintLog(' ', 0)
Пример #26
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()
Пример #27
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
Пример #28
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
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")
Пример #30
0
def getChannels(subFolder):
    gd = GenericDialog("Channel Options")

    gd.addMessage("Name the markers associated with this directory:")
    gd.addMessage(inputDirectory + subFolder)
    gd.addMessage("(Leave empty to ignore)")
    gd.addMessage("")
    gd.addStringField("Channel ch00:", "Dapi")
    gd.addStringField("Channel ch01:", "pSYN")
    gd.addStringField("Channel ch02:", "MAP2")
    gd.addStringField("Channel ch03:", "SYN")
    gd.addMessage("")
    gd.addStringField("What would you like the output file to be named:",
                      "output")

    gd.showDialog()

    channelNames = []

    channelNames.append([gd.getNextString(), 0])
    channelNames.append([gd.getNextString(), 1])
    channelNames.append([gd.getNextString(), 2])
    channelNames.append([gd.getNextString(), 3])
    outputName = gd.getNextString()

    channels = []
    for i, v in enumerate(channelNames):
        if v[0] != "":
            channels.append(v)

    if gd.wasCanceled():
        print
        "User canceled dialog!"
        return

    return channels, outputName
def analysis_parameters_gui(rerun_analysis=False, params=None):
	"""GUI for setting analysis parameters at the start of a run. TODO: more effectively separate model and view"""
	if params is None:
		params = Parameters(load_last_params = True);
	dialog = GenericDialog("Analysis parameters");
	controls = [];
	if rerun_analysis:
		params.setUseSingleChannel(False);
		params.togglePerformUserQC(False);
		params.setDoInnerOuterComparison(False);

	controls.append(MyControlDefinition(u'Curvature length parameter (\u00b5m): ', 
									 MyControlDefinition.Numeric, 
									 round(params.curvature_length_um, 2), 
									 params.setCurvatureLengthUm));
	controls.append(MyControlDefinition(u'Width of region for intensity analysis (\u00b5m): ', 
									MyControlDefinition.Numeric, 
									round(params.intensity_profile_width_um, 2), 
									params.setIntensityProfileWidthUm))
	controls.append(MyControlDefinition("Threshold method: ",
									 MyControlDefinition.Choice, 
									 params.threshold_method, 
									 params.setThresholdMethod, 
									 choices=params.listThresholdMethods(), 
									 enabled=(not rerun_analysis)));
	controls.append(MyControlDefinition("Curvature overlay LUT: ", 
									 MyControlDefinition.Choice, 
									 params.curvature_overlay_lut_string, 
									 params.setCurvatureOverlayLUT, 
									 choices=IJ.getLuts()));
	controls.append(MyControlDefinition("Curvature kymograph LUT: ",
									 MyControlDefinition.Choice, 
									 params.curvature_kymograph_lut_string, 
									 params.setCurvatureKymographLUT, 
									 choices=IJ.getLuts()));
	controls.append(MyControlDefinition("Labelled species kymograph LUT: ", 
									 MyControlDefinition.Choice, 
									 params.actin_kymograph_lut_string, 
									 params.setActinKymographLUT, 
									 choices=IJ.getLuts()));
	controls.append(MyControlDefinition("Labelled species for intensity analysis: ", 
									 MyControlDefinition.String, 
									 params.labeled_species, 
									 params.setLabeledSpecies));
	controls.append(MyControlDefinition("Use intensity channel for segmentation too?", 
									 MyControlDefinition.Checkbox, 
									 params.use_single_channel, 
									 params.setUseSingleChannel, 
									 enabled=(not rerun_analysis)));
	controls.append(MyControlDefinition("Metadata source: ", 
									 MyControlDefinition.RadioButtonGroup, 
									 params.metadata_source, 
									 params.setMetadataSource, 
									 choices=["Image metadata", "Acquisition metadata"]));
	controls.append(MyControlDefinition("Constrain anchors close to manual selections?", 
									 MyControlDefinition.Checkbox, 
									 params.constrain_anchors, 
									 params.toggleConstrainAnchors, 
									 enabled=(not rerun_analysis)));
	controls.append(MyControlDefinition("Filter out negative curvatures", 
									 MyControlDefinition.Checkbox, 
									 params.filter_negative_curvatures, 
									 params.setFilterNegativeCurvatures));
	controls.append(MyControlDefinition("Account for photobleaching?", 
									 MyControlDefinition.Checkbox, 
									 params.photobleaching_correction, 
									 params.togglePhotobleachingCorrection));
	controls.append(MyControlDefinition("Perform quality control of membrane edges?", 
									 MyControlDefinition.Checkbox, 
									 params.perform_user_qc, 
									 params.togglePerformUserQC, 
									 enabled=(not rerun_analysis)));
	controls.append(MyControlDefinition("Perform quality control of background regions?", 
									 MyControlDefinition.Checkbox, 
									 params.qc_background_rois, 
									 params.toggleBackgroundQc));
	controls.append(MyControlDefinition("Perform spatial cropping?", 
									 MyControlDefinition.Checkbox, 
									 params.perform_spatial_crop, 
									 params.toggleSpatialCrop, 
									 enabled=(not rerun_analysis)));
	controls.append(MyControlDefinition("Perform time cropping?",
									 MyControlDefinition.Checkbox, 
									 params.perform_time_crop, 
									 params.toggleTimeCrop, 
									 enabled=(not rerun_analysis)));
	controls.append(MyControlDefinition("Close images on completion?", 
									 MyControlDefinition.Checkbox, 
									 params.close_on_completion, 
									 params.toggleCloseOnCompletion));
	controls.append(MyControlDefinition("Compare inner and outer curvature regions?", 
									 MyControlDefinition.Checkbox, 
									 params.inner_outer_comparison, 
									 params.setDoInnerOuterComparison, 
									 enabled=(not rerun_analysis)));
	for control in controls:
		control.addControl(dialog);
	dialog.showDialog();
	if dialog.wasCanceled():
		raise KeyboardInterrupt("Run canceled");

	numeric_controls = [c for c in controls if c.control_type==MyControlDefinition.Numeric];
	for nc, nf in zip(numeric_controls, dialog.getNumericFields()):
		nc.setter(float(nf.getText()));
	string_controls = [c for c in controls if c.control_type==MyControlDefinition.String];
	for sc, sf in zip(string_controls, dialog.getStringFields()):
		sc.setter(sf.getText());
	choice_controls = [c for c in controls if c.control_type==MyControlDefinition.Choice];
	for cc, cf in zip(choice_controls, dialog.getChoices()):
		cc.setter(cf.getSelectedItem());
	checkbox_controls = [c for c in controls if c.control_type==MyControlDefinition.Checkbox];
	for cbc, cbf in zip(checkbox_controls, dialog.getCheckboxes()):
		cbc.setter(cbf.getState());
	radiobuttongroup_controls = [c for c in controls if c.control_type==MyControlDefinition.RadioButtonGroup];
	for rbc in radiobuttongroup_controls:
		rbc.setter(rbc.checkboxes[[cb.getState() for cb in rbc.checkboxes].index(True)].getLabel());

	params.persistParameters();
	return params;
Пример #32
0
    #    return
    # Prevent further propagation of the key event:
    keyEvent.consume()


# MAIN code
imp = IJ.getImage()
killIt = False
if imp.getHeight() == 1024:  # half-chip size
    hOffset = 512
elif imp.getHeight() == 2048:  #full-chip image
    hOffset = 0
else:
    gdGoodBye = GenericDialog("Dimensions error")
    gdGoodBye.addMessage(
        'Image must be 2048x2048, or 2048x1024 pixels! \n I retire!')
    gdGoodBye.showDialog()
    killIt = True

if not killIt:
    IJ.setTool(Toolbar.RECTANGLE)
    manager = RoiManager.getInstance()
    if manager is None:
        manager = RoiManager()
    reset()
    listener = ML()
    keyLis = ListenToKey()
    win = imp.getWindow()
    win.getCanvas().addMouseListener(listener)
    win.getCanvas().addKeyListener(keyLis)
Пример #33
0
def pause_for_debug():
    gd = GenericDialog("Continue?")
    gd.showDialog()
    if gd.wasCanceled():
        raise Exception("Run interupted")
def processDirectory():
	# start logging
	IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n")

	# ask user for an input directory
	dc = DirectoryChooser("Choose folder containing Olympus (.oir) files")  
	inputDir = dc.getDirectory() 
	if inputDir is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  
	IJ.log("\nInput directory: " + inputDir + "\n")

	oirFiles = []
	for f in os.listdir(inputDir):
		if f.endswith(".oir"):
			oirFiles.append(f)

	if len(oirFiles) < 1:
		IJ.log("Input directory does not contain any Olympus (.oir) files.\nNo images to process.\n")
		return
  	
	# find out how many channels are in first file (we will assume all files have same number of channels and were acquired using same DMs)
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(inputDir + oirFiles[0])
	numChannels = reader.getSizeC()

	# ask user to identify dichroic mirror used for each channel  
	gdDM = GenericDialog("Dichroic mirrors")
	DMs = ["DM1", "DM2", "DM3", "DM4", "DM5"] 
	for i in range(numChannels):
		gdDM.addChoice("Channel " + str(i+1), DMs, DMs[0])
	gdDM.addCheckbox("Merge channels", False) 
	gdDM.showDialog()
	if gdDM.wasCanceled():
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
		return
	dichroics = []
	for i in range(numChannels):
		dichroics.append(gdDM.getNextChoice())
	merge = gdDM.getNextBoolean()
	IJ.log("User selected dichroic mirrors")
	for i in range(numChannels):
		IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i])
	IJ.log("\n")

	if merge:
		channels = []
		chDict = {}
		for i in range(numChannels):
			chName = "Channel"+str(i+1)
			channels.append(chName)
			chDict[chName] = i
		channels.append("NONE")
		colourChoices = ["red", "green", "blue", "gray", "cyan", "magenta", "yellow"]
		gdMerge = GenericDialog("Merge channels")
		for c in colourChoices:
			gdMerge.addChoice(c + ":", channels, channels[numChannels])
		gdMerge.showDialog()
		if gdMerge.wasCanceled():
			IJ.log("User canceled the dialog!\nImage processing canceled!\n")
			return
		IJ.log("User selected channel colours")
		usersMergeList = []
		for i in range(len(colourChoices)):
			ch = gdMerge.getNextChoice()
			if ch == "NONE":
				usersMergeList.append(None)
			else:
				usersMergeList.append(chDict[ch])
				IJ.log("\t\t" + colourChoices[i] + ": " + ch)
		IJ.log("\n\n")

	# ask user for an output directory
	dc = DirectoryChooser("Choose folder for output")  
	outputDir = dc.getDirectory()    
	if outputDir is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  

	counter = 0
	totalFiles = len(oirFiles)
	for o in oirFiles:
		counter +=1
		IJ.log("Processing file " + str(counter) + " of " + str(totalFiles) + "\n")
		IJ.log("File path: " + inputDir + o)
		if merge:
			ml = usersMergeList[:]
		else:
			ml = None
		processFile(o, inputDir, outputDir, dichroics, ml)
		IJ.log("\n--------------------------\n")
Пример #35
0
def Options(sourceFolder):
    #globals
    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())]
    numTifs = len(tifNames)

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

    gd.addMessage('Source Folder: ' + sourceFolder)
    gd.addMessage('Number of .tif files: ' + str(numTifs))

    #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)

    #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'
        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('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
def run():
    types = ['oneDay', 'oneFolder', 'oneFile', 'mapmaneger', 'test']

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

    if gd.wasCanceled():
        print 'user cancel the plugin'
        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):
                bab.bPrintLog(
                    '\nERROR: runOneDay() did not find folder: ' + dayFolder +
                    '\n', 0)
                return 0

            dirNames = [
                file for file in os.listdir(dayFolder)
                if os.path.isdir(os.path.join(dayFolder, file))
            ]
            numDirs = len(dirNames)
            bab.bPrintLog('dayFolder is:' + dayFolder, 0)
            bab.bPrintLog('Number of subFolders: ' + str(numDirs), 1)
            #put option here so we do not have to click for each folder
            if bab.Options(dayFolder + dirNames[0] + '/'):
                for dirName in dirNames:
                    #sourceFolder = os.path.join(dayFolder, dirName) # did not add '/' to the end
                    sourceFolder = dayFolder + '/' + dirName + '/'
                    bab.runOneFolder(sourceFolder)

        #run one folder
        if srcType == 1:
            sourceFolder = DirectoryChooser(
                'Please Choose A Directory Of .tif Files').getDirectory()
            if not sourceFolder:
                exit(1)
            if bab.Options(sourceFolder):
                bab.runOneFolder(sourceFolder)

        #run one file
        if srcType == 2:
            od = OpenDialog("Choose image file", None)
            srcDirectory = od.getDirectory()
            srcFile = od.getFileName()
            if srcFile != None and bab.Options(srcDirectory):
                bab.runOneFile(srcDirectory + srcFile)

        if srcType == 3:  #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 = ','", mapNames, 50)
            gd.showDialog()
            if gd.wasCanceled():
                bab.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:
                bab.bPrintLog('\nERROR: no map folder found', 0)
                return 0

            bab.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/' for mapFolder in mapFolders
            ]
            if bab.Options(sourceFolders[0]):
                for sourceFolder in sourceFolders:
                    bab.runOneFolder(sourceFolder)

        if srcType == 4:  #for test
            gd = GenericDialog('Choose maps')
            gd.addStringField('maps name initials', 'F58,F59')
            gd.showDialog()
            maps = gd.getNextString().split(',')
            maps = tuple(maps)
            bab.bPrintLog(maps[0], 0)
Пример #37
0
from pharynx_analysis.utils import *

###################################################
# SETUP

imTitles = WindowManager.getImageTitles()
nTitles = len(imTitles)

## DIALOG
d = GenericDialog("Measure")
d.addChoice("Mask", imTitles, "-")
d.addChoice("470 image", imTitles, "-")
d.addChoice("410 image", imTitles, "-")
d.addRadioButtonGroup("Binning", ["4x4", "2x2"], 1, 2, "4x4")
d.showDialog()

imgMask = WindowManager.getImage(d.getNextChoice())
img470 = WindowManager.getImage(d.getNextChoice())
img410 = WindowManager.getImage(d.getNextChoice())

binning = d.getNextRadioButton()

PARENT_DIR = img410.getOriginalFileInfo().directory

# setup data collection object
dataTable = ResultsTable()

##################################################
# INITIAL MEASUREMENTS
table = ResultsTable()
def processFile():
	# start logging
	IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n")

	# ask user for file
	ofd = OpenDialog("Choose a file", None)  
	filename = ofd.getFileName()  
  
	if filename is None:  
  		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
  		return

  	directory = ofd.getDirectory()  
  	filepath = directory + filename  
  	IJ.log("File path: " + filepath)

	if not filename.endswith(".oir"):
		IJ.log("Not an Olympus (.oir) file.\nNo image to process.\n")
		return

	filenameExExt = os.path.splitext(filename)[0]
      
	# parse metadata
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(filepath)
	numChannels = reader.getSizeC()
	numSlices = reader.getSizeZ()
	numFrames = reader.getSizeT()
	seriesCount = reader.getSeriesCount()

	globalMetadata = reader.getGlobalMetadata()
	seriesMetadata = reader.getSeriesMetadata()

	objLensName = globalMetadata['- Objective Lens name #1']

	areaRotation = float(seriesMetadata['area rotation #1'])
	acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1'])
	if 'regionInfo rotation #1' in seriesMetadata:
		regionInfoRotation = float(seriesMetadata['regionInfo rotation #1'])
	else:
		regionInfoRotation = float(0)

	totalRotation = areaRotation + regionInfoRotation
	physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
	physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
	pxSizeX = physSizeX.value(UNITS.MICROM)
	pxSizeY = physSizeY.value(UNITS.MICROM)

	# log metadata
	IJ.log("\nMETADATA")
	#IJ.log("Filename: " + filepath)
	IJ.log("Number of series: " + str(seriesCount))
	IJ.log("Number of channels: " + str(numChannels))
	IJ.log("Number of frames: " + str(numFrames))
	IJ.log("Number of slices: " + str(numSlices))
	IJ.log("Objective lens: " + objLensName)
	IJ.log("FOV rotation: " + str(areaRotation))
	IJ.log("ROI rotation: " + str(regionInfoRotation))
	IJ.log("Total rotation: " + str(totalRotation))
	IJ.log("Pixel size:")
	IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol())
	IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol())

	# ask user to identify dichroic mirror used for each channel  
	gdDM = GenericDialog("Dichroic mirrors")
	DMs = ["DM1", "DM2", "DM3", "DM4", "DM5"] 
	for i in range(numChannels):
		gdDM.addChoice("Channel " + str(i+1), DMs, DMs[0])
	gdDM.addCheckbox("Merge channels", False) 
	gdDM.showDialog()
	if gdDM.wasCanceled():
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
		return
	dichroics = []
	for i in range(numChannels):
		dichroics.append(gdDM.getNextChoice())
	merge = gdDM.getNextBoolean()
	IJ.log("\nUser selected dichroic mirrors")
	for i in range(numChannels):
		IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i])	

	if merge:
		channels = []
		chDict = {}
		for i in range(numChannels):
			chName = "Channel"+str(i+1)
			channels.append(chName)
			chDict[chName] = i
		channels.append("NONE")
		colourChoices = ["red", "green", "blue", "gray", "cyan", "magenta", "yellow"]
		gdMerge = GenericDialog("Merge channels")
		for c in colourChoices:
			gdMerge.addChoice(c + ":", channels, channels[numChannels])
		gdMerge.showDialog()
		if gdMerge.wasCanceled():
			IJ.log("User canceled the dialog!\nImage processing canceled!\n")
			return
		IJ.log("\nUser selected channel colours")
		mergeList = []
		for i in range(len(colourChoices)):
			ch = gdMerge.getNextChoice()
			if ch == "NONE":
				mergeList.append(None)
			else:
				mergeList.append(chDict[ch])
				IJ.log("\t\t" + colourChoices[i] + ": " + ch)

	# ask user for an output directory
	dc = DirectoryChooser("Choose folder for output")  
	od = dc.getDirectory()    
	if od is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  
  
	if merge:
		tifDir = od + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated temporary folder: " + tifDir + "\n")
		else:
			IJ.log("Unable to create temporary folder!\n")
	else:
		tifDir = od + filenameExExt + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated subfolder: " + tifDir + "\n")
		else:
			IJ.log("\nSubfolder " + tifDir +  " already exists")

	# correct images
	tifFilePaths = []
	for i in range(numChannels):
		ip = extractChannel(oirFile=filepath, ch=i)
		if dichroics[i] == "DM1":
			IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.")
		else:
			offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]])
			xom = offsets['x']
			yom = offsets['y']
			if abs(totalRotation) > 0.1:
				rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation)
				xom = rotOff['x']
				yom = rotOff['y']
			xop = int(round(xom/pxSizeX))
			yop = int(round(yom/pxSizeY))
			IJ.log("Channel " + str(i+1) + " offsets")
			IJ.log("\t\tMicrometres")
			IJ.log("\t\t\t\tx = " + str(xom))
			IJ.log("\t\t\t\ty = " + str(yom))
			IJ.log("\t\tPixels")
			IJ.log("\t\t\t\tx = " + str(xop))
			IJ.log("\t\t\t\ty = " + str(yop))
			IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack")

		tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif"
		tifFilePaths.append(tifFilePath)
		if os.path.exists(tifFilePath):
			IJ.log("\nOutput file exists: " + tifFilePath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
			return
		FileSaver(ip).saveAsTiff(tifFilePath)

	if merge:
		for i in range(len(mergeList)):
			if mergeList[i] != None:
				mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]])
		merged = RGBStackMerge.mergeChannels(mergeList, False)
		mergedChannelFilepath = od + filenameExExt + ".tif"
		if os.path.exists(mergedChannelFilepath):
			IJ.log("\nOutput file exists: " + mergedChannelFilepath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
		FileSaver(merged).saveAsTiff(mergedChannelFilepath)
		for tf in tifFilePaths:
			os.remove(tf)
		os.rmdir(tifDir)
			
	IJ.log("\nFinished processing file:\n" + filepath + "\n")
	if merge:
		IJ.log("Image file with channels aligned:\n" + od + filenameExExt + ".tif\n")
	else:
		IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
Пример #39
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()
Пример #40
0
keep_rois = [];
pa.analyze(imp);

IJ.run("Set Measurements...", "centroid redirect=None decimal=3");
frames = imp.getNFrames();	
for fridx in range(0, frames):
	rt.reset();
	imp.setSliceWithoutUpdate(fridx + 1);
	ip = imp.getProcessor();
	if not pa.analyze(imp, ip):
		raise Exception("something went wrong analysing particles!")
	rt.show("centroids");
	rm = RoiManager.getInstance();
	if rm.getCount() > 0:
		rois = rm.getRoisAsArray();
		centroidsx = rt.getColumn(rt.getColumnIndex('X'));
		centroidsy = rt.getColumn(rt.getColumnIndex('Y'));
		print(centroidsx);
		print(centroidsy);
		gd = GenericDialog("Continue?");
		gd.showDialog();
		if gd.wasCanceled():
			raise Exception("Run interupted");
		for roi in rois:
			imp.setRoi(roi);
			stats = ImageStatistics().getStatistics(ip);
			print(stats.xCenterOfMass)
			

#print(keep_rois)
Пример #41
0
def batch_open_images(pathImage, file_typeImage, name_filterImage=None):

    if isinstance(pathImage, File):
        pathImage = pathImage.getAbsolutePath()

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filterImage:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filterImage, (list, tuple)):
                for name_filter_ in name_filterImage:
                    if name_filter_ in string:
                        # Exit the function with True.

                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filterImage, string):
                if name_filterImage in string:
                    return True
                else:
                    return False
            return False
        else:
            # Accept all files if name_filter is None.
            return True

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_typeImage:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_typeImage, (list, tuple)):
                for file_type_ in file_typeImage:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_typeImage, string):
                if string.endswith(file_typeImage):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathImage)
    path = os.path.expandvars(pathImage)
    # If we don't want a recursive search, we can use os.listdir().

    for directory, dir_names, file_names in os.walk(pathImage):
        # We are only interested in files.
        for file_name in file_names:
            # The list contains only the file names.
            # The full path needs to be reconstructed.
            full_path = os.path.join(directory, file_name)
            # Both checks are performed to filter the files.
            if check_type(file_name):
                if check_filter(file_name) is False:
                    # Add the file to the list of images to open.
                    path_to_Image.append([
                        full_path,
                        os.path.basename(os.path.splitext(full_path)[0])
                    ])
    Images = []

    for img_path, file_name in path_to_Image:

        imp = IJ.openImage(img_path)
        maskimage = ops.run("create.img", imp)
        cursor = maskimage.localizingCursor()
        imp.show()
        IJ.run("Select None")
        overlay = imp.getOverlay()
        if overlay == None:

            overlay = Overlay()
            imp.setOverlay(overlay)
        else:

            overlay.clear()

        imp.updateAndDraw()
        impY = imp.getHeight()
        impX = imp.getWidth()
        print(impY, impX)
        rm = RoiManager.getInstance()
        if not rm:
            rm = RoiManager()

        rm.runCommand("reset")
        WaitForUserDialog("Select the landmark and the second point").show()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()
        for Roi in roi_points:

            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Start Landmark', xpoints[0], ypoints[0])
        fixedpointX = xpoints[0]
        fixedpointY = ypoints[0]
        print('End Landmark', xpoints[1], ypoints[1])
        IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1])
        gui = GenericDialog("Rotation Angle")
        gui.addNumericField("Choose Angle", 15, 0)
        gui.showDialog()
        if gui.wasOKed():

            rotateangle = gui.getNextNumber()
            IJ.run("Rotate...", "angle=" + str(int(float(rotateangle))))

        rm.runCommand("reset")
        overlay = imp.getOverlay()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()

        for Roi in roi_points:
            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Rotated Start Landmark', xpoints[0], ypoints[0])
        print('Rotated End Landmark', xpoints[1], ypoints[1])
        slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20)
        intercept = fixedpointY - slope * fixedpointX
        print(fixedpointX, fixedpointY)
        print('Slope', slope, 'Intercept', intercept)
        XwY0 = -intercept / slope
        YxwY0 = slope * XwY0 + intercept

        XwYmax = (impY - intercept) / slope
        YxwYmax = slope * XwYmax + intercept

        YwX0 = intercept
        XywX0 = (YwX0 - intercept) / slope
        YwXmax = impX * slope + intercept
        XxwXmax = (YwXmax - intercept) / slope
        rm.runCommand("reset")

        if XwY0 > 0:
            lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0)
            lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        if XwY0 < 0:
            lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0)
            lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        while cursor.hasNext():
            cursor.fwd()
            X = cursor.getDoublePosition(0)
            Y = cursor.getDoublePosition(1)
            if abs(Y - slope * X - intercept) <= 4:
                cursor.get().set(0)
            else:
                cursor.get().set(1)
        labeling = ops.labeling().cca(maskimage,
                                      StructuringElement.EIGHT_CONNECTED)

        # get the index image (each object will have a unique gray level)
        labelingIndex = labeling.getIndexImg()
        dataImg = ds.create(labelingIndex)
        location = ls.resolve(
            str(savedir) + '/' + file_name + '.' + file_type_image)
        dio.save(dataImg, location)
        imp.close()
Пример #42
0
def settings():
    """ Settings """

    # Calls potential config file to set defaults
    # for settings dialog. Sets all defaults to 0
    # if no config file exists.
    con_path = os.path.join(str(Root), "FRET_params.cfg")
    if os.path.exists(con_path):
        dflt = config_read()
        print type(dflt.get("b_sub", "Rolling ball"))
        print (dflt.get("b_sub", "Rolling ball"))
        print type(int(dflt.get("b_sub", "Rolling ball")))
        print (dflt.get("b_sub", "Rolling ball"))
    else:
        dflt = {}

    feat_model_strings = ["Translation", "Rigid", 
                          "Similarity", "Affine
                          ]
    reg_model_strings = ["Translation", "Rigid",
                         "Similarity", "Affine",
                         "Elastic", "Least Squares"
                         ]
    b_sub_strings = ["Rolling Ball", "Manual Selection"]
                         
    # Registration parameters dialog.
    gd = GenericDialog("Advanced Settings")
    gd.addMessage("REGISTRATION PARAMETERS") 
    gd.addNumericField("Steps per scale octave: ", float(dflt.get("steps", 6)), 0, 7, "")
    gd.addNumericField("Max Octave Size: ", float(dflt.get("max_oct", 1024)), 0, 7, "")
    gd.addNumericField("Feature Descriptor Size: ", float(dflt.get("fd_size", 12)), 1, 7, "")
    gd.addNumericField("Initial Sigma: ", float(dflt.get("sigma", 1.2)), 2, 7, "")  
    gd.addNumericField("Max Epsilon: ", float(dflt.get("max_eps", 15)), 1, 7, "")
    gd.addNumericField("Min Inlier Ratio: ", float(dflt.get("min_inlier", 0.05)), 3, 7, "")
    gd.addCheckbox("Use Shrinkage Constraint", ast.literal_eval(dflt.get("shrinkage", "False")))
    gd.addChoice("Feature extraction model", feat_model_strings,
                 feat_model_strings[int(dflt.get("feat_model", 1))]
                 )
    gd.addChoice("Registration model", reg_model_strings,
                 reg_model_strings[int(dflt.get("reg_model", 1))]
                 )
    
    # Background removal parameters dialog.
    gd.addPanel(Panel())
    gd.addMessage("BACKGROUND REMOVAL") 
    gd.addChoice("Subtraction method:", b_sub_strings,
                 b_sub_strings[int(dflt.get("b_sub", 0))]
                 )          
    gd.addNumericField("Rolling ball size: ", 
                       float(dflt.get("ballsize", 50)), 1, 7, "px"
                       )
    gd.addCheckbox("Create Background", ast.literal_eval(dflt.get("create_b", "False")))
    gd.addCheckbox("Light Background", ast.literal_eval(dflt.get("light_b", "False")))
    gd.addCheckbox("Use Parabaloid", ast.literal_eval(dflt.get("parab", "False")))
    gd.addCheckbox("Do Pre-smoothing", ast.literal_eval(dflt.get("smooth", "False")))
    gd.addCheckbox("Correct Corners", ast.literal_eval(dflt.get("corners", "False")))

    # Measumrent parameters dialog.
    gd.addPanel(Panel())
    gd.addMessage("MEASUREMENT PARAMETERS")
    gd.addNumericField("Max Cell Area", float(dflt.get("cell_max", 2200)), 0, 7, "px")
    gd.addNumericField("Min Cell Area", float(dflt.get("cell_min", 200)), 0, 7, "px")
    gd.addNumericField("Ratio Subtraction", float(dflt.get("subtr_ratio", 0.31)), 3, 7, "")

    # Plot parameters dialog.
    gd.addPanel(Panel())
    gd.addMessage("PLOT PARAMETERS")
    gd.addNumericField("Max y, d and aFRET", float(dflt.get("p_max", 0.65)), 2, 7, "")
    gd.addNumericField("Min y, d and aFRET", float(dflt.get("p_min", 0.0)), 2, 7, "")
    gd.addNumericField("Max y, norm. d and aFRET", float(dflt.get("p_max_n", 1.65)), 2, 7, "")
    gd.addNumericField("Min y, norm. d and aFRET", float(dflt.get("p_min_n", 0.5)), 2, 7, "")
    
    # Set location of dialog on screen.
    #gd.setLocation(0,1000)
    
    gd.showDialog()
    
    # Checks if cancel was pressed, kills script.
    if gd.wasCanceled() is True:
        sys.exit("Cancel was pressed, script terminated.")

    # Parameters dictionary.
    parameters = {"steps" : gd.getNextNumber(), 
                 "max_oct" : gd.getNextNumber(),
                 "fd_size" : gd.getNextNumber(),
                 "sigma" : gd.getNextNumber(),
                 "max_eps" : gd.getNextNumber(),
                 "min_inlier" : gd.getNextNumber(),
                 "shrinkage" : gd.getNextBoolean(),
                 "feat_model" : gd.getNextChoiceIndex(),
                 "reg_model" : gd.getNextChoiceIndex(),
                 "b_sub" : gd.getNextChoiceIndex(),
                 "ballsize" : gd.getNextNumber(),
                 "create_b" : gd.getNextBoolean(),
                 "light_b" : gd.getNextBoolean(),
                 "parab" : gd.getNextBoolean(),
                 "smooth" : gd.getNextBoolean(),
                 "corners" : gd.getNextBoolean(),
                 "cell_max" : gd.getNextNumber(),
                 "cell_min" : gd.getNextNumber(),
                 "subtr_ratio" : gd.getNextNumber(),
                 "p_max" : gd.getNextNumber(),
                 "p_min" : gd.getNextNumber(),
                 "p_max_n" : gd.getNextNumber(),
                 "p_min_n" : gd.getNextNumber()
                 }

    parameters = config_write(parameters)   

    return parameters
def main():
    #print (sys.version_info) # debug
    #print(sys.path) # debug
    data_root = r'C:\Users\dougk\Desktop\test'
    # debug
    output_root = r'C:\Users\dougk\Desktop\test'
    #debug
    #default_directory = r'C:\\Users\\Doug\\Desktop\\test';
    #data_root, output_root = file_location_chooser(default_directory);
    if (data_root is None) or (output_root is None):
        raise IOError("File location dialogs cancelled!")
    timestamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H.%M.%S")
    output_path = os.path.join(output_root, (timestamp + " output"))
    for file_path in filterByFileType(os.listdir(data_root), '.tif'):
        subfolder_name = os.path.splitext(file_path)[0]
        output_subfolder = os.path.join(output_path, subfolder_name)
        print(output_subfolder)
        os.makedirs(output_subfolder)
        imps = bf.openImagePlus(os.path.join(data_root, file_path))
        imp = imps[0]
        imp.show()
        h = imp.height
        w = imp.width
        slices = imp.getNSlices()
        channels = imp.getNChannels()
        frames = imp.getNFrames()

        # rotation step - since using multiples of 90, TransformJ.Turn is more efficient
        IJ.run("Enhance Contrast", "saturated=0.35")
        angleZ = 1
        while ((angleZ % 90) > 0):
            gd = GenericDialog("Rotate?")
            gd.addMessage(
                "Define rotation angle - increments of 90. Apical at top")
            gd.addNumericField("Rotation angle", 0, 0)
            gd.showDialog()
            angleZ = int(gd.getNextNumber())

        if (angleZ > 1):
            IJ.run("TransformJ Turn",
                   "z-angle=" + str(angleZ) + " y-angle=0 x-angle=0")
            imp.close()
            imp = WindowManager.getCurrentImage()
            imp.setTitle(file_path)

        # trim time series
        IJ.run("Enhance Contrast", "saturated=0.35")
        imp.setDisplayMode(IJ.COLOR)
        WaitForUserDialog(
            "Scroll to the first frame of the period of interest and click OK"
        ).show()
        start_frame = imp.getT()
        WaitForUserDialog(
            "Scroll to the last frame of the period of interest and click OK"
        ).show()
        end_frame = imp.getT()
        trim_imp = Duplicator().run(imp, 1, channels, 1, slices, start_frame,
                                    end_frame)
        imp.close()
        trim_imp.show()
        dup_imp = Duplicator().run(trim_imp)

        # create images to process and find bounds for
        dup_imps = ChannelSplitter().split(dup_imp)
        myo_imp = dup_imps[1]
        mem_imp = dup_imps[0]
        FileSaver(myo_imp).saveAsTiffStack(
            os.path.join(output_subfolder, "myosin_channel.tif"))
        FileSaver(mem_imp).saveAsTiffStack(
            os.path.join(output_subfolder, "membrane_channel.tif"))

        # set basal bounds
        myo_imp.show()
        ImageConverter(myo_imp).convertToGray8()
        frames = myo_imp.getNFrames()
        gb = GaussianBlur()
        for fridx in range(0, frames):
            myo_imp.setSliceWithoutUpdate(fridx + 1)
            ip = myo_imp.getProcessor()
            gb.blurGaussian(ip, 5.0, 1.0, 0.02)
            # assymmetrical Gaussian
        IJ.run(myo_imp, "Convert to Mask",
               "method=Otsu background=Dark calculate")
        IJ.run("Despeckle", "stack")
        title = myo_imp.getTitle()

        # assume that first frame is good quality image...
        basal_edges = find_basal_edges(myo_imp)
        #myo_imp.hide()
        mem_imp.hide()

        # draw some edges for checking
        roim = RoiManager()
        xs = [x for x in range(1,
                               trim_imp.getWidth() + 1)]
        trim_imp.show()
        for fridx in range(0, myo_imp.getNFrames()):
            trim_imp.setPosition(2, 1, fridx + 1)
            IJ.run("Enhance Contrast", "saturated=0.35")

            roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE)
            trim_imp.setRoi(roi)
            roim.addRoi(roi)
Пример #44
0
def run():
    '''This is the main function run when the plugin is called.'''

    #print dir(IJ)
    ip = IJ.getProcessor()

    imp = IJ.getImage()  # get the current Image, which is an ImagePlus object
    #print "imp=", type(imp), imp
    #print dir(imp)

    roi = imp.getRoi()  # get the drawn ROI
    #print "roi=", roi, roi.getClass()

    # check ROI type
    if roi == None:
        gd = GenericDialog("Draw Measurement - Line")
        gd.addMessage("Please draw a straight-line first!")
        gd.showDialog()
        return
        #raise Exception(  "Please draw a line ROI first!" )
    if roi.getTypeAsString() != "Straight Line":
        gd = GenericDialog("Draw Measurement - Line")
        gd.addMessage("Please draw a straight-line first!")
        gd.showDialog()
        return
        #raise Exception(  "Not a Line ROI!  (type="+roi.getTypeAsString()+")"  )

    p1 = [int(roi.x1d), int(roi.y1d)]  # point 1 (x,y)
    p2 = [int(roi.x2d), int(roi.y2d)]  # point 2
    print "DrawMeas(): Line Points: p1=", p1, " & p2=", p2
    pm = midpoint(p1, p2)  # get midpoint coord

    # set ROI params from settings:
    ''' Using new method - used ip.drawLine instead of roi.draw, since roi.draw didn't always apply the line thickness.  Would be best to use the ROI method, in case other types of ROI's could be annotated.
    
    roi.setStrokeWidth( sets.linethickness )
    roi.setStrokeColor(  jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3]))  )
    
    #roi.drawPixels( ip )   # draw along the ROI - only draws outline unfortunately
    ip.drawRoi(roi)     # draw the ROI on the image
    '''

    ip.setLineWidth(int(sets.linethickness))
    ip.setColor(
        jColor(float(sets.linecolor[0]), float(sets.linecolor[1]),
               float(sets.linecolor[2]), float(sets.linecolor[3])))

    #ip.draw(roi)   # changed to ip.drawLine()
    ip.drawLine(int(roi.x1d), int(roi.y1d), int(roi.x2d), int(roi.y2d))
    '''Draw text annotation'''
    unit = imp.getCalibration().getUnit().encode(
        'utf8')  # get the unit as UTF-8 (for \mu)
    print "Draw_Meas(): Unit (raw) = `", unit, "`", type(unit),
    if unit[0] == u'\xc2': unit = unit[1:]  # strip weird char at start of \mu

    # format of measurement text (eg. 3 decimal points):
    lenstr = "%0.3f" % roi.getLength() + " %s" % (
        unit)  # string to print as length
    print "DrawMeas(): Line length= %s" % lenstr
    #print "x,y=", p2[0], p2[1]
    '''determine position of text from line coords, eg "bottom right" or "top left" etc.   '''
    # y-coord:
    if p2[1] > p1[1]:
        posstr = 'bottom'
    else:
        posstr = 'top'

    # x-coord:
    if p2[0] > p1[0]:
        posstr += ' right'
    else:
        posstr += ' left'

    drawText(lenstr, p2[0], p2[1], position=posstr)

    imp.updateAndDraw()  #update the image
		return True;

activation_overlay_data = ActivationOverlayMetadata(lowMagM=m2, highMagM=m1, scanImageDimensionsXY=(x_image_size_pix,y_image_size_pix));

dialog = GenericDialog("Define 5x ROI parameters...");
dialog.addNumericField("ROI X position (software coordinates, pixels): ", 0, 0);
dialog.addNumericField("ROI Y position (software coordinates, pixels): ", 0, 0);
dialog.addNumericField("ROI width (pixels): ", 0, 0);
dialog.addNumericField("ROI height (pixels): ", 0, 0);
dialog.addNumericField("3x ROI X offset pixels: ", 0, 0);
dialog.addNumericField("3x ROI Y offset pixels: ", 0, 0);
dialog.addNumericField("Pan X (um): ", 0, 3);
dialog.addNumericField("Pan Y (um): ", 0, 3);
dialog.addNumericField("Frame interval (s): ", 1.0, 2);

dialog.showDialog();

x5x = dialog.getNextNumber();
y5x = dialog.getNextNumber();
w5x = dialog.getNextNumber();
h5x = dialog.getNextNumber();
activation_overlay_data.setRoi((x5x,y5x,w5x,h5x));
offsetx = dialog.getNextNumber();
offsety = dialog.getNextNumber();
activation_overlay_data.setLowMagOffsetXY((offsetx,offsety));
panx = dialog.getNextNumber();
pany = dialog.getNextNumber();
activation_overlay_data.setPanUmXY((panx,pany));
interval = dialog.getNextNumber();
activation_overlay_data.setFrameIntervalS(interval);
Пример #46
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)
Пример #47
0
def main():

    # start with the sequence parameters
    fieldNames = ["Number of views", "Number of projections for each view",
                  "Number of images for each projection (normally 1)",
                  "Number of flats in each set", "Number of darks in each set",
                  "Number of projections between each set of flats/darks"]
    fieldValues = []  # we start with zeros for the values

    # get user variables with imageJ dialog
    dialog = GenericDialog("Enter Scan Information")
    for i in range(6):
        dialog.addNumericField(fieldNames[i], 0, 0)
    dialog.addCheckbox("Two sets flats/darks between views?", False)
    dialog.showDialog()
    if dialog.wasCanceled():
        return  # exit function
    for i in range(6):
        fieldValues.append(int(dialog.getNextNumber()))
    extra = dialog.getNextBoolean()
    # make sure that none of the fields was left blank
    errmsg = ""
    for i in range(len(fieldNames)):
        if fieldValues[i] == "":
            errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
        try:
            int(fieldValues[i])
        except ValueError:
            errmsg += ('"%s" has to be an integer value.\n\n' %
                       fieldNames[i])
    if fieldValues[1] and fieldValues[5]:
        if int(fieldValues[1]) % int(fieldValues[5]) != 0:
            errmsg += ('Flat/Dark interval must divide evenly into projections\n\n')
    if errmsg != "":
        err_msg = GenericDialog("Error in Input")
        err_msg.addMessage(errmsg)
        err_msg.showDialog()
        return  # exit
    if fieldValues is None:
        return  # exit function
    fieldValues = [int(i) for i in fieldValues]
    # get the first item of the sequence using an imageJ dialog
    openFile = OpenDialog(
        "Select the first file of the sequence to rename.", None)
    fileName = openFile.getFileName()
    if fileName is None:
        return  # exit function
    fileDir = openFile.getDirectory()
    first = fileDir + fileName
    path1, filename = os.path.split(first)
    basename = short(filename)
    # get directory for new files using imageJ dialog
    openOutDir = DirectoryChooser("Select directory for new files.")
    path2 = openOutDir.getDirectory()
    if path2 is None:
        return  # exit function
    new_seq, fd_seq = gen_seq(fieldValues[0], fieldValues[1], fieldValues[2],
                              fieldValues[3], fieldValues[4], fieldValues[5],
                              extra)
    result = rename(basename, new_seq, fd_seq, path1, path2, fieldValues[0])
    print result
Пример #48
0
class Colortags:
'''
This class handles persistence of the name of different color channels.
It instantiates a GUI window to capture and show the color names in use.
Other classes such as ColorMerger needs this to determine the color of the channel being processed.
'''
	def __init__(self):

		self.window = None
		self.tags = {}
		self.prefkeys = ["{0}.{1}".format(SUBKEY, name) for name in COLORS]
		self.userprefs = Prefs()
		self.load()
		while not self.tags:
			self.edit("Please set at least one colortag.\n\n")


	def load(self):
		'''
		Tries to load IBPlib colortags from IJ prefs.
		'''
		for i in range(7):
			storedtags = self.userprefs.getString(".{0}".format(self.prefkeys[i]), "")
			if not storedtags:
				continue
			trimmedtagslist = [t.strip() for t in storedtags.split(",")]
			self.tags.update({i:trimmedtagslist})


	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 __validate(self):

		fields = self.window.getStringFields()
		newvalues = {}
		for i in range(len(fields)):
			txt = fields[i].getText()
			newvalues.update({i: txt.strip()})
		return newvalues


	def __savetags(self):

		newvalues = self.__validate()
		for i, tags in newvalues.items():
			key = self.prefkeys[i]
			self.userprefs.set(key, tags)
			self.userprefs.savePreferences()
Пример #49
0
def uScopeCalDialog(cal):
    ''' Pop up a dialog asking user to edit line settings etc.
     
    CalIdx, SetGlobalScale, AddScaleBar = uScopeCalDialog(cal) 
     
    `cal` should be the object containing `names`, `cals`, `units` attributes 
    as set in the "user_settings.py" file. 
     
    `CalIdx` is the list index to the chosen calibration.   
        Eg., if the options were  
            ['5x', '10x', '20x'] 
        and the user chose '10x', then  
            CalIdx = 1 
        Returns `None` if the user cancelled the dialog. 
     
    `SetGlobalScale` is a boolean (True/False) from a checkbox option, if the user wants this calibration set 'globally' to all open images. 
     
    `AddScaleBar` is also a boolean (True/False), for a checkbox option, if user would like to run "Scale Bar..." afterwards. 
    '''

    # The following inspired heavily by Correct_3D_drift.py:

    #print "uScopeCalDialog():"
    #print cal.names, [str(x) for x in cal.cals]

    gd = GenericDialog("Microscope Calibrations")
    gd.addMessage("Choose the calibration to load:")

    # generate text to display in list:
    # Radio Buttons:
    CalStr = []
    CalType_IsFunc = []

    for ii, name in enumerate(cal.names):
        if MC_DEBUG:
            print("item #%i: name=" % (ii), name, "\n\t type=", type(name))
        if isinstance(name, basestring):
            '''It's just a regular calibration setting'''
            CalStr.append(name + "      (%s" % cal.cals[ii] +
                          " pixels/%s)" % cal.units[ii])
        else:
            ''' Assume we'll be loading a custom function/class '''
            CalStr.append(
                name.name)  # get the name from the Class' .name attribute
        #end if(str)
    #end for(cal.names)
    '''if > 20 cals, use dropdown list, otherwise use radio buttons'''
    if len(cal.names) > 20:
        Radio = False
        # Drop-Down list:
        gd.addChoice("     Calibration:", CalStr,
                     CalStr[0])  # default = 1st (#0)

    else:
        Radio = True
        gd.addRadioButtonGroup("     Calibration:", CalStr, len(CalStr), 1,
                               CalStr[0])
        #addRadioButtonGroup(label, [String items],  rows,  columns,  String:defaultItem)
    #end if(cal>20)

    gd.addCheckbox("Apply Scale to all open images?", False)
    gd.addCheckbox("Add Scale Bar to this image?", False)
    gd.addMessage(
        "These calibrations can be altered by editing the file: \nFiji.app/plugins/Scripts/Plugins/Analyze/...\n\tMicroscope Measurement Tools/...\n\tMicroscope_Calibrations_user_settings.py"
    )

    gd.showDialog()

    if gd.wasCanceled():
        return None, None, None  # return None's if user cancels

    if Radio:
        ChosenCal = gd.getNextRadioButton()
        # Find the index to the chosen radio button w/ [list].index():
        CalIdx = CalStr.index(ChosenCal)
    else:
        ChosenCal = gd.getNextChoiceIndex()
        CalIdx = ChosenCal  # the index to the choice

    SetGlobalScale = gd.getNextBoolean()
    AddScaleBar = gd.getNextBoolean()

    #if MC_DEBUG: print( ChosenCal,CalIdx, SetGlobalScale )
    #if MC_DEBUG: print( "end uScopeCalDialog()." )
    return CalIdx, SetGlobalScale, AddScaleBar
Пример #50
0
def display_msg(title, message):
    gd = GenericDialog(title)
    gd.addMessage(message)
    gd.hideCancelButton()
    gd.showDialog()
Пример #51
0
            eventOutL = slider3_feedback + 1 + slider2_feedback * (
                ch * frames) + evt * (zplanes * ch * frames)
            imp.setPosition(1, eventOutL, 1)
        else:
            eventOutL = frames + slider3_feedback + 1 + slider2_feedback * (
                ch * frames) + evt * (zplanes * ch * frames)
            imp2.setPosition(1, eventOutL, 1)


# Define the pre-conditions for loading the data, default values represent my normal acquisition parameters only the loop has to be set, the rest is read from metadata

psgd = GenericDialog("Pre-Set")
psgd.addCheckbox(
    "Images open?", False
)  # if your images  are already open as a virtual stack, you can avoid to load again
psgd.showDialog()

if psgd.wasOKed():
    choiceIm = psgd.getCheckboxes().get(0).getState()

    # load data as virtual stack, simple image stack
    if choiceIm == False:
        IJ.run("Close All", "")
        impDir = OpenDialog("Select the 6D dataset").getPath()
        impDir = impDir.replace("\\", "/")

        IJ.run(
            "Bio-Formats", "open=" + impDir +
            " color_mode=Default display_metadata rois_import=[ROI manager] view=[Standard ImageJ] stack_order=Default use_virtual_stack"
        )
def main():
    # define here which membrane indices will be used in the analysis, with last index the "control" index
    membrane_indices = [-1, 0, 1, 3]

    # for now, work with frontmost open image...
    imp = IJ.getImage()
    im_title = imp.getTitle()
    settings = MembraneEvolutionAnalysisSettings(
        membrane_indices=membrane_indices)
    settings.loadPersistedSettings()

    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    DirectoryChooser.setDefaultDirectory((settings.output_path))
    dc = DirectoryChooser('Select the root folder for saving output')
    output_root = dc.getDirectory()
    if output_root is None:
        raise IOError('no output path chosen')
    settings.output_path = output_root

    # get calibration
    cal = imp.getCalibration()
    if cal.getTimeUnit() == "sec":
        cal.setTimeUnit('s')

    # pop up a dialog prompting for selection of zero time point, frame interval, and time step for analysis
    time_steps_not_ok = True
    while time_steps_not_ok:
        dialog = NonBlockingGenericDialog("Determine time parameters...")
        dialog.addNumericField("0 timepoint frame (1-index): ",
                               settings.zero_timepoint_frame, 0)
        dialog.addNumericField("Acquisition time step (s): ",
                               cal.frameInterval,
                               2)  # assume stored in seconds
        dialog.addNumericField(
            "Time step for analysis (s): ",
            cal.frameInterval * settings.analysis_frame_step, 2)
        dialog.showDialog()

        if dialog.wasCanceled():
            return

        zero_f = dialog.getNextNumber()
        acq_t_step = dialog.getNextNumber()
        analysis_t_step = dialog.getNextNumber()
        if acq_t_step != 0 and analysis_t_step != 0:
            analysis_frame_step = analysis_t_step / acq_t_step

            if round(analysis_frame_step) == analysis_frame_step:
                time_steps_not_ok = False
                settings.zero_timepoint_frame = zero_f
                settings.analysis_frame_step = analysis_frame_step
        if time_steps_not_ok:
            warning_dlg = GenericDialog("Error!")
            warning_dlg.addMessage(
                "Analysis time step must be an integer multiple of acquisition time steps, and neither should be zero!!"
            )
            warning_dlg.setOKLabel("Try again...")
            warning_dlg.showDialog()

            if warning_dlg.wasCanceled():
                return

    start_frame = int(((zero_f - 1) % analysis_frame_step) + 1)
    end_frame = int(imp.getNFrames() -
                    (imp.getNFrames() - zero_f) % analysis_frame_step)
    frames = [
        f + 1
        for f in range(start_frame - 1, end_frame, int(analysis_frame_step))
    ]
    print("frames = " + str(frames))
    imp.killRoi()
    analysis_imp = SubstackMaker().makeSubstack(
        imp,
        str(start_frame) + "-" + str(end_frame) + "-" +
        str(int(analysis_frame_step)))
    imp.changes = False
    imp.close()
    analysis_imp.show()
    drawn_membranes = [
        TimepointsMembranes(input_image_title=im_title,
                            time_point_s=(t - 1) * acq_t_step) for t in frames
    ]
    membranes_listener = UpdateRoiImageListener(drawn_membranes)
    analysis_imp.addImageListener(membranes_listener)

    # now attach roi listener to store all 0th membranes after showing a waitforuserdialog to prompt continuation
    IJ.setTool("freeline")
    for membrane_idx in membrane_indices:
        #		if membrane_idx>50:
        #			IJ.setTool("line");
        analysis_imp.killRoi()
        membranes_listener.resetLastFrame()
        membranes_listener.setCurrentMembraneIndex(membrane_idx)
        analysis_imp.setZ(1)
        continue_dlg = WaitForUserDialog(
            "Continue?", "Click OK once all the " + str(membrane_idx) +
            "-index membranes have been drawn")
        continue_dlg.show()
        membranes_listener.imageUpdated(analysis_imp)
        drawn_membranes = membranes_listener.getDrawnMembraneTimepointsList()
        json_path = os.path.join(output_root,
                                 "Membranes " + timestamp + ".json")
        f = open(json_path, 'w+')
        try:
            json.dump(drawn_membranes, f, default=encode_membrane)
        finally:
            f.close()
        # save csv containing mebrane measurements for current membrane index
        csv_path = os.path.join(
            output_root, ("Membrane measurements " + timestamp + ".csv"))
        if membrane_idx == membrane_indices[0]:
            try:
                f = open(csv_path, 'wb')
                writer = csv.writer(f)
                writer.writerow([
                    "Membrane index", ("Time point, " + cal.getTimeUnit()),
                    ("Membrane length, " + cal.getUnit()),
                    ("Euclidean length, " + cal.getUnit()),
                    "Membrane sinuoisty"
                ])
            finally:
                f.close()
        try:
            f = open(csv_path, 'ab')
            writer = csv.writer(f)
            for mems in drawn_membranes:
                mem = mems.getMembrane(membrane_idx)
                if mem is not None:
                    writer.writerow([
                        membrane_idx, mems.time_point_s,
                        mem.getPathLength() * cal.pixelWidth,
                        mem.getEuclidean() * cal.pixelWidth,
                        mem.getSinuosity()
                    ])
        finally:
            f.close()

    settings.persistSettings()
    settings.save_settings()
    print("Finished getting all membranes with indices " +
          str(membrane_indices))
    analysis_imp.close()
Пример #53
0
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()
	if gui.wasOKed():
	    LOCAL_PREDICTION_SCRIPT   = gui.getNextString()
Пример #54
0
def main():
    metadatas = []
    runagain = True
    offsetx = 0
    offsety = 0
    interval = 50.0
    IJ.run(imp, "RGB Color", "")
    IJ.run("Colors...", "foreground=cyan background=white selection=yellow")
    while runagain:
        dialog = GenericDialog("Define 5x ROI parameters...")
        dialog.enableYesNoCancel("Continue and quit",
                                 "Continue and add another line")
        dialog.addNumericField("Line scan position 1 X, Y: ", 0, 0)
        dialog.addToSameRow()
        dialog.addNumericField(", ", 0, 0)
        dialog.addNumericField("Line scan position 2 X, Y: ", 0, 0)
        dialog.addToSameRow()
        dialog.addNumericField(", ", 0, 0)
        dialog.addNumericField("Reference image crop origin X, Y: ", offsetx,
                               0)
        dialog.addToSameRow()
        dialog.addNumericField(", ", offsety, 0)
        dialog.addNumericField("Frame interval (s): ", interval, 2)

        dialog.showDialog()

        p1x = dialog.getNextNumber()
        p1y = dialog.getNextNumber()
        p2x = dialog.getNextNumber()
        p2y = dialog.getNextNumber()
        offsetx = dialog.getNextNumber()
        offsety = dialog.getNextNumber()
        interval = dialog.getNextNumber()
        linescan_overlay = LineScanOverlayMetadata(
            (p1x, p1y), (p2x, p2y), (offsetx, offsety), interval)
        metadatas.append(linescan_overlay)
        roi = linescan_overlay.generateOverlayRoi()
        imp.setRoi(roi)
        IJ.run("Draw", "stack")

        if dialog.wasOKed():
            runagain = False
        elif dialog.wasCanceled():
            return

    sd = SaveDialog("Save as AVI...",
                    os.path.splitext(imp.getTitle())[0],
                    "line scan overlay.avi")
    if sd.getFileName is not None:
        metadatas[0].save_to_json(
            os.path.join(
                sd.getDirectory(),
                os.path.splitext(os.path.basename(sd.getFileName()))[0] +
                "line scan metadata.json"))
        if len(
                metadatas
        ) > 1:  # append: multiple writes=slow, but easiest way based on existing framework
            for midx in range(1, len(metadatas)):
                metadatas[midx].save_to_json(os.path.join(
                    sd.getDirectory(),
                    os.path.splitext(os.path.basename(sd.getFileName()))[0] +
                    "line scan metadata.json"),
                                             append=True)
        IJ.saveAs(
            imp, "Tiff",
            os.path.join(
                sd.getDirectory(),
                os.path.splitext(os.path.basename(sd.getFileName()))[0] +
                " + line scan ROI, no timestamp.tif"))
        IJ.run(
            imp, "Label...",
            "format=00:00:00 starting=0 interval=" + str(interval) +
            " x=5 y=20 font=18 text=[] range=1-" + str(imp.getNFrames()))
        IJ.run(
            imp, "AVI... ", "compression=None frame=10 save=[" +
            os.path.join(sd.getDirectory(),
                         (os.path.splitext(sd.getFileName())[0] +
                          " + line scan ROI.avi")) + "]")
        IJ.saveAs(
            imp, "Tiff",
            os.path.join(
                sd.getDirectory(),
                os.path.splitext(os.path.basename(sd.getFileName()))[0] +
                " + line scan ROI.tif"))
Пример #55
0
    # save roi
    if rm.getCount() != 0:
        rm.runCommand('Save', os.path.join(result_path, 'Roi.zip'))

    zimp.close()
    imp.close()
    rm.close()
    zrt.reset()

if __name__ in ['__builtin__','__main__']:
    # ask file path via dialog
    open_file_dialog = OpenDialog('Opend file')
    path = open_file_dialog.getPath()

    # ask parameter via dialog
    parameter_dialog = GenericDialog('Parameter setting')
    parameter_dialog.addNumericField('Frame number', 1000,0)
    parameter_dialog.addNumericField('Frame rate (frame/s)', 100, 1)
    parameter_dialog.addChoice('Are motor rotation direction and cell rotation direction on image same?', 
                               ['Same', 'Different'], 'Same')
    parameter_dialog.showDialog()
    frame_number = int(parameter_dialog.getNextNumber())
    frame_rate = 100.0
    choice = parameter_dialog.getNextChoice()
    if choice == 'Same':
        CCW = 1
    else:
        CCW = -1
    tethered_cell(path, frame_number, frame_rate, CCW)
    IJ.log('analysis finished')
Пример #56
0
    measurements_filename = imp_title[:-4]
    IJ.saveAs("Results", "{}{}.csv".format(path, measurements_filename))
    IJ.selectWindow("Results")
    IJ.run("Close")
    IJ.log("Measurements saved at {}{}.csv".format(path,
                                                   measurements_filename))
    # Close the active image so IJ can move on to the next
    imp.close()


n_images = WindowManager.getImageCount()
i = 0
while i < n_images:
    measure_rois()
    i += 1

# Clear ROI manager (after OKing with user) so that there aren't still
# ROIs that will be used in next measurement
gd = GenericDialog("ROI deletion warning")
gd.addMessage("Do you wish to clear current ROIs?")
gd.enableYesNoCancel()
choice = gd.showDialog()
roim = RoiManager.getInstance()

if gd.wasCanceled():
    pass
elif gd.wasOKed():
    roim.reset()
else:
    print("NO")
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
		for i in anchorTiles:
			if (i+stepSize-1 > finishTile):
				lastAnchorTile = finishTile
			else:
				lastAnchorTile = i+stepSize-1
Пример #58
0
def run():
    ### Default arguments
    two_sarcomere_size = 25  # determined by filter used.
    rotation_angle = 0.0

    ### Get the image we'd like to work with.
    # Don't need to ask where to save the intermediate image since it'll just be saved in the matchedmyo folder anyway
    #   may change this though. In case they want to keep that image around.
    this_img = WindowManager.getCurrentImage()
    if this_img == None:
        ud = WaitForUserDialog(
            "Please select the image you would like to analyze.")
        ud.show()
        this_img = WindowManager.getCurrentImage()
    img_name = this_img.getTitle()

    matchedmyo_path = "/home/AD/dfco222/scratchMarx/matchedmyo/"  # this would be grabbed from the prompt
    gd = GenericDialog("Preprocessing Options")
    gd.addCheckbox("Automatic Resizing/Rotation", True)
    gd.addCheckbox("CLAHE", True)
    gd.addCheckbox("Normalization to Transverse Tubules", True)
    gd.showDialog()
    if gd.wasCanceled():
        return
    auto_resize_rotate = gd.getNextBoolean()
    clahe = gd.getNextBoolean()
    normalize = gd.getNextBoolean()

    if auto_resize_rotate:
        # Clear selection so it takes FFT of full image

        rotation_angle = auto_resize_angle_measure(this_img,
                                                   two_sarcomere_size)

    if clahe:
        clahe_args = "blocksize={} histogram=256 maximum=3 mask=*None* fast_(less_accurate)".format(
            two_sarcomere_size)
        IJ.run(this_img, "Enhance Local Contrast (CLAHE)", clahe_args)

    if normalize:
        # Ask the user to select a subsection of the image that looks healthy-ish.
        ud = WaitForUserDialog(
            "Please select a subsection exhibiting a measure of healthy TT structure using the Rectangle tool.\n"
            + " Only a single cell or several are needed.\n\n" +
            " Press 'OK' when finished.")
        ud.show()
        IJ.setTool("rectangle")

        # Duplicate the selected subsection.
        selection = this_img.crop()
        IJ.run(selection, "Duplicate...", "title=subsection.tif")

        # Grab the subsection image and rotate it.
        selection = WindowManager.getImage("subsection.tif")
        IJ.run(
            selection, "Rotate...",
            "angle={} grid=1 interpolation=Bicubic enlarge".format(
                rotation_angle))

        # Ask the user to select a bounding box that contains only tubules
        # NOTE: Need to get rid of initial selection since it's the entire image and it's annoying to click out of
        IJ.setTool("rectangle")
        IJ.run(selection, "Select None", "")
        ud = WaitForUserDialog(
            "Select a subsection of the image that contains only tubules and no membrane."
        )
        ud.show()

        # Grab the subsection ImagePlus
        selection = WindowManager.getCurrentImage()
        this_window = WindowManager.getActiveWindow()
        selection_small = selection.crop()
        IJ.run(selection, "Close", "")

        # NOTE: May not actually display this depending on how the macros work
        IJ.run(selection_small, "Duplicate...", "title=subsection_small.tif")

        # Smooth the selection using the single TT filter.
        # NOTE: It won't read in so we're just going to hard code it in since it's simple
        tt_filt_row = "0 0 0 1 1 1 1 1 1 0 0 0 0\n"
        tt_filt = ""
        for i in range(21):
            tt_filt += tt_filt_row
        IJ.run("Convolve...", "text1=[" + tt_filt + "] normalize")

        # Segment out the TTs from the 'gaps' using Gaussian Adaptive Thresholding.
        selection_small = WindowManager.getImage("subsection_small.tif")
        IJ.run(selection_small, "Duplicate...", "title=thresholded.tif")
        threshed = WindowManager.getImage("thresholded.tif")
        IJ.run(threshed, "Auto Local Threshold",
               "method=Bernsen radius=7 parameter_1=1 parameter_2=0 white")

        # Select the TTs from the thresholded image.
        IJ.run(threshed, "Create Selection", "")
        tt_selection = WindowManager.getImage("subsection_small.tif")
        IJ.selectWindow("thresholded.tif")
        IJ.selectWindow("subsection_small.tif")
        IJ.run(tt_selection, "Restore Selection", "")

        # Get TT intensity statistics.
        stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV
        stats = IS.getStatistics(tt_selection.getProcessor(), stat_options,
                                 selection_small.getCalibration())
        # Calculate pixel ceiling intensity value based on heuristic.
        # TODO: Add a catch for data type overflow.
        pixel_ceiling = stats.mean + 3 * stats.stdDev
        print "px ceil:", pixel_ceiling

        # Invert selection to get inter-sarcomeric gap intensity statistics.
        IJ.run(tt_selection, "Make Inverse", "")
        stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV
        stats = IS.getStatistics(tt_selection.getProcessor(), stat_options,
                                 selection_small.getCalibration())
        # Calculate pixel floor intensity value based on heuristic.
        pixel_floor = stats.mean - stats.stdDev
        # TODO: Add a catch for data type underflow.
        print "px floor:", pixel_floor

        # Threshold original image based on these values.
        IJ.selectWindow(this_img.getTitle())
        IJ.run(this_img, "Select All", "")
        IJ.setMinAndMax(pixel_floor, pixel_ceiling)
        IJ.run(this_img, "Apply LUT", "")

    ## Ask if it is acceptable.
    gd = GenericDialog("Acceptable?")
    gd.addMessage(
        "If the preprocessed image is acceptable for analysis, hit 'OK' to being analysis.\n"
        + " If the image is unacceptable or an error occurred, hit 'Cancel'")
    gd.showDialog()
    if gd.wasCanceled():
        return

    ## Save the preprocessed image.
    imp = IJ.getImage()
    fs = FileSaver(imp)
    img_save_dir = matchedmyo_path + "myoimages/"  # actually get from user at some point
    img_file_path = img_save_dir + img_name[:-4] + "_preprocessed.tif"
    if os.path.exists(img_save_dir) and os.path.isdir(img_save_dir):
        print "Saving image as:", img_file_path
        if os.path.exists(img_file_path):
            # use dialog box to ask if they want to overwrite
            gd = GenericDialog("Overwrite?")
            gd.addMessage(
                "A file exists with the specified path, \"{}\". Would you like to overwrite it?"
                .format(img_file_path))
            gd.enableYesNoCancel()
            gd.showDialog()
            if gd.wasCanceled():
                return
        elif fs.saveAsTiff(img_file_path):
            print "Preprocessed image saved successfully at:", '"' + img_file_path + '"'
    else:
        print "Folder does not exist or is not a folder!"

    ### Create the YAML file containing the parameters for classification
    ## Ask user for YAML input
    gd = GenericDialog("YAML Input")
    gd.addStringField("imageName", img_file_path, 50)
    #gd.addStringField("maskName", "None")
    gd.addStringField("outputParams_fileRoot", img_file_path[:-4], 50)
    gd.addStringField("outputParams_fileType", "tif")
    gd.addNumericField("outputParams_dpi", 300, 0)
    gd.addCheckbox("outputParams_saveHitsArray", False)
    gd.addStringField("outputParams_csvFile", matchedmyo_path + "results/")
    gd.addCheckbox("TT Filtering", True)
    gd.addToSameRow()
    gd.addCheckbox("LT Filtering", True)
    gd.addToSameRow()
    gd.addCheckbox("TA Filtering", True)
    gd.addNumericField("scopeResolutions_x", 5.0, 3)
    gd.addToSameRow()
    gd.addNumericField("scopeResolutions_y", 5.0, 3)
    gd.addMessage("Enter in filter rotation angles separated by commas.")
    gd.addStringField("", "-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25", 50)
    gd.addCheckbox("returnAngles", False)
    gd.addCheckbox("returnPastedFilter", True)
    gd.showDialog()
    if gd.wasCanceled():
        return

    strings = [st.text for st in gd.getStringFields()]
    #if strings[1] == "None" or "":
    #	strings[1] = None
    nums = [float(num.text) for num in gd.getNumericFields()]
    nums[0] = int(nums[0])  # Have to make sure the dpi variable is an integer
    checks = [str(bool(boo.state)) for boo in gd.getCheckboxes()]
    iter_argument = ','.join(
        [str(float(it) - rotation_angle) for it in strings[4].split(',')])
    string_block = """imageName: {0[0]}
outputParams:
  fileRoot: {0[1]}
  fileType: {0[2]}
  dpi: {1[0]}
  saveHitsArray: {2[0]}
  csvFile: {0[3]}
preprocess: False
filterTypes:
  TT: {2[1]}
  LT: {2[2]}
  TA: {2[3]}
scopeResolutions:
  x: {1[1]}
  y: {1[2]}
iters: [{3}]
returnAngles: {2[4]}
returnPastedFilter: {2[5]}""".format(strings, nums, checks, iter_argument)
    im_title = this_img.getTitle()
    with cd(matchedmyo_path):
        yaml_file_path = "./YAML_files/" + im_title[:-4] + ".yml"
        with open("./YAML_files/" + im_title[:-4] + ".yml", "w") as ym:
            ym.write(string_block)
        print "Wrote YAML file to:", matchedmyo_path + yaml_file_path[2:]

    ### Run the matchedmyo code on the preprocessed image
    with cd(matchedmyo_path):
        #os.chdir(matchedmyo_path)
        #subprocess.call(["python3", matchedmyo_path+"matchedmyo.py", "fullValidation"])
        subprocess.call(
            ["python3", "matchedmyo.py", "run", "--yamlFile", yaml_file_path])
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

            imp.show()
            IJ.setForegroundColor(255, 255, 255)
Пример #60
0
else:

    # List column headers
    table = tableWindow.getResultsTable()
    headers = table.getHeadings()

    # Generate dialog with dropdown for column selection
    dialog = GenericDialog("PieChart from table column")
    dialog.addChoice("Data column", headers, headers[0])
    dialog.addMessage(
        """Hover the mouse over the plot to view absolute and relative (%) values\n
	Right-click to set colors, export to PNG...\n
	Note: BarCharts usually provide better distinction than PieCharts for sectors with similar sizes (see Help)."""
    )
    dialog.addHelp(r"https://www.data-to-viz.com/caveat/pie.html")
    dialog.showDialog()

    # Generate PieChart with data column
    if dialog.wasOKed():

        # Get the data column as string
        selectedHeader = dialog.getNextChoice()
        column = table.getColumnAsVariables(selectedHeader)
        columnString = [str(item)[1:-1]
                        for item in column]  # [1:-1] to remove the ""

        # Make the PieChart for this data column
        if columnString:
            chart = PieChart(selectedHeader, columnString)
            chart.showFrame("PieChart")