def showOptionsDialog(self):
		gd = GenericDialog("my cool tool options")
		gd.addNumericField("min. size: ", self.minSize)
		gd.showDialog()
		if gd.wasCanceled():
			return None
		self.minSize = gd.getNextNumber()
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
Пример #3
0
def start_masking_menu():

    wlist = WindowManager.getImageTitles()
    gd = GenericDialog('Masking - Setup')
    gd.setCancelLabel('Exit')

    gd.addChoice('Create mask from', wlist, wlist[0])
    gd.addNumericField("Gaussian blur:", 0, 1)
    gd.addNumericField("Fixed threshold:", 0, 0)
    gd.addCheckbox('Use automatic thresholding', False)
    gd.addChoice('Method', ['Default', 'Huang', 'Otsu', 'Yen'], 'Default')

    gd.showDialog()

    if gd.wasCanceled():
        return False

    pdic = {}

    pdic['sel_win'] = gd.getNextChoice()
    pdic['sigma'] = gd.getNextNumber()
    pdic['threshold'] = gd.getNextNumber()
    pdic['use_auto'] = gd.getNextBoolean()
    pdic['thresh_method'] = gd.getNextChoice()

    return pdic
Пример #4
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.")
        print ">>>> No image to work with!"
        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():
            print ">>>> User canceled dialog!"
            canProceed = False
        else:
            xradius = gd.getNextNumber()
            yradius = gd.getNextNumber()
            zradius = gd.getNextNumber()

    return canProceed
Пример #5
0
    def setupDialog(imp):

        gd = GenericDialog("Toolbox options")
        gd.addMessage("Imagej toolbox, you are analyzing: " + imp.getTitle())
        calibration = imp.getCalibration()

        if (calibration.frameInterval > 0):
            default_interval = calibration.frameInterval
            default_timeunit = calibration.getTimeUnit()

        else:
            default_interval = 10
            default_timeunit = "sec"

        gd.addNumericField("Frame interval:", default_interval,
                           2)  # show 2 decimals
        #    gd.addCheckbox("Do you want to use a gliding window?", True)
        #    gd.addCheckbox("Project hyperStack? (defaluts to projecting current channel only)", False)
        #    gd.addStringField("time unit",default_timeunit, 3)
        #    gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1)
        #    gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames())
        #    gd.addNumericField("Number of frames to project in to one:", 3, 0)  # show 0 decimals

        gd.addChoice('Method to use for stack background filtering:',
                     methods_as_strings, methods_as_strings[5])

        gd.showDialog()

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

        return gd
def scaleImageUI():  
	gd = GenericDialog("Scale")  
	gd.addSlider("Scale", 1, 200, 100)  
	gd.addCheckbox("Preview", True)  
	# The UI elements for the above two inputs  
	slider = gd.getSliders().get(0) # the only one  
	checkbox = gd.getCheckboxes().get(0) # the only one  
	
	imp = WM.getCurrentImage()  
	if not imp:  
		print "Open an image first!"  
		return  
	
	previewer = ScalingPreviewer(imp, slider, checkbox)  
	slider.addAdjustmentListener(previewer)  
	checkbox.addItemListener(previewer)  
		
	gd.showDialog()  
	
	if gd.wasCanceled():  
		previewer.reset()  
		print "User canceled dialog!"  
	else:  
		previewer.scale()  
	
	previewer.destroy()  
Пример #7
0
def split_and_save(imp):
	base_title = imp.getShortTitle()
	base_dir = imp.getOriginalFileInfo().directory
	
	d = GenericDialog("Split Stacks")
	d.addMessage("Indicate the channels in your image stack, separated by commas")
	d.addMessage("Add the channels *in the order that you took the images*")
	d.addMessage("For example, \"TL, 410, 470, 410, 470\"")
	d.addStringField("Channels", "TL, 470, 410", 40)
	d.showDialog()
	# exit if cancelled
	if d.wasCanceled():
		return None
	
	channels = number_duplicate_channels([x.strip() for x in d.getNextString().split(',')])
	
	# Check that the number of images in stack is divisible by the number of channels
	# If not, quit. Else keep going
	if (imp.getNSlices() % len(channels) != 0):
		IJ.error("Invalid Channel Specification", "The number of slices (%d) is not divisible by the number of channels (%d). Exiting." % (imp.getNSlices(), len(channels)))
		return None
	imp.show()
	IJ.run("Deinterleave", "how=%d" % len(channels))

	for i, img_id in enumerate(WindowManager.getIDList()):
		channel_i = WindowManager.getImage(img_id)
		channel_i.setTitle(base_title + "_" + channels[i])
		IJ.saveAs(channel_i, "tif", base_dir + channel_i.getTitle())
	IJ.showMessage("Saved image stacks as separate channels in %s" % base_dir)
Пример #8
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      
Пример #9
0
def getOptions(imp):
  gd = GenericDialog("Correct 2D/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("Correct only x & y (for 3D data):", False)
  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.addNumericField("Only consider pixels with values larger than:", 0, 0)
  gd.addNumericField("Lowest z plane to take into account:", 1, 0)
  gd.addNumericField("Highest z plane to take into account:", imp.getNSlices(), 0)
  gd.addCheckbox("Use virtualstack for saving the results to disk to save RAM?", False)
  gd.addCheckbox("Only compute drift vectors?", False)
  gd.addMessage("If you put a ROI, drift will only be computed in this region;\n the ROI will be moved along with the drift to follow your structure of interest.")
  gd.showDialog()
  if gd.wasCanceled():
    return
  channel = gd.getNextChoiceIndex() + 1  # zero-based
  correct_only_xy = gd.getNextBoolean()
  multi_time_scale = gd.getNextBoolean()
  subpixel = gd.getNextBoolean()
  process = gd.getNextBoolean()
  background = gd.getNextNumber()
  z_min = gd.getNextNumber()
  z_max = gd.getNextNumber()
  virtual = gd.getNextBoolean()
  only_compute = gd.getNextBoolean()
  return channel, virtual, multi_time_scale, subpixel, process, background, z_min, z_max, only_compute, correct_only_xy
Пример #10
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
Пример #11
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())
def canceled():
    gd = GenericDialog("Caution")
    gd.addMessage('Tiff file(s) already exists in {}.\n \
    The file may be replaced by this macro run. Do you wish to continue?'.
                  format(save_dir))
    gd.showDialog()
    return gd.wasCanceled()
Пример #13
0
def getOptions():
    gd = GenericDialog("Options")
    gd.addCheckbox("Process_Right_Camera?", True)
    gd.addCheckbox("Process_Left_Camera?", True)
    gd.addNumericField("CamRScale: ", 214, 0)
    gd.addNumericField("CamLScale: ", 202, 0)
    gd.addNumericField("BackgroundWindowStart: ", 0, 0)
    gd.addNumericField("BackgroundWindowEnd: ", 600, 0)
    gd.addNumericField("GridSize: ", 10000, 0)
    gd.addNumericField("TranslateR: ", 0, 0)
    gd.addNumericField("TranslateL: ", 0, 0)
    gd.showDialog()
    #
    if gd.wasCanceled():
        print "User canceled dialog!"
        return
    # Read out the options
    runCamR = gd.getNextBoolean()
    runCamL = gd.getNextBoolean()
    CamRScale = gd.getNextNumber()
    CamLScale = gd.getNextNumber()
    BackgroundWindowStart = gd.getNextNumber()
    BackgroundWindowEnd = gd.getNextNumber()
    GridSize = gd.getNextNumber()
    TranslateR = gd.getNextNumber()
    TranslateL = gd.getNextNumber()
    return runCamR, runCamL, CamRScale, CamLScale, BackgroundWindowStart, BackgroundWindowEnd, GridSize, TranslateR, TranslateL  # a tuple with the parameters
Пример #14
0
def getChannels(subFolder):
    gd = GenericDialog("Channel Options")

    gd.addMessage("Name the markers associated with these subfolder:")
    gd.addMessage(subFolder)
    gd.addMessage("(Leave empty to ignore)")
    gd.addMessage("")
    gd.addStringField("Channel d0:", "Dapi")
    gd.addStringField("Channel d1:", "Tuj1")
    gd.addStringField("Channel d2:", "GFAP")
    gd.addStringField("Channel d3:", "syn")
    gd.addMessage("")

    gd.showDialog()

    channelNames = []

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

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

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

    return channels
Пример #15
0
def getOptions():
    global listener, xlist, ylist, zlist, manager
    gd = GenericDialog("Target Selection")
    gd.addChoice('type', ['point', 'circle', 'spiral'], 'point')
    gd.addNumericField("                power (%)", 85, 0)
    gd.addNumericField("                duration (ms)", 1, 0)
    gd.addNumericField("                radius(circle/spiral)", 5, 0)
    gd.addNumericField("                # revolutions (circle/spiral)", 3, 0)
    gd.addNumericField(
        "                add CAMERA_TRIGGER after every (entries)", 1, 0)
    gd.addNumericField("                Prewait between entries (ms)", 5000, 0)
    gd.addNumericField("                Z-start of stack (um)", 0, 0)
    gd.addNumericField("                Z-step of stack (um)", 5, 0)
    gd.addMessage('Press ENTER to save\n')
    gd.addMessage('Press ESC to restart\n')
    gd.showDialog()
    profileType = gd.getNextChoice()
    power = gd.getNextNumber()
    duration = gd.getNextNumber()
    r = gd.getNextNumber()
    Nturns = gd.getNextNumber()
    camTriggerEvery = gd.getNextNumber()
    prewait = gd.getNextNumber()
    zStart = gd.getNextNumber()
    zStep = gd.getNextNumber()
    if gd.wasCanceled():
        IJ.setTool(Toolbar.RECTANGLE)
        return
    else:
        return r, power, profileType, duration, Nturns, camTriggerEvery, zStart, zStep, prewait
def get_info():
    srcDir = IJ.getDirectory("Input_Directory")
    if not srcDir:
        print("No input directory selected")
        return
    dstDir = IJ.getDirectory("Output_Directory")
    if not dstDir:
        print("No output directory selected")
        return
    gd = GenericDialog("Process Folder")
    gd.addStringField("File_extension", ".lif")
    gd.addStringField("File_name_contains", "")
    gd.addCheckbox("Keep directory structure when saving", True)
    gd.showDialog()
    if gd.wasCanceled():
        return
    ext = gd.getNextString()
    containString = gd.getNextString()
    keepDirectories = gd.getNextBoolean()
    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            # Check for file extension
            if not filename.endswith(ext):
                continue

# Check for file name pattern
            if containString not in filename:
                continue
            print(srcDir)
            print(filename)
            process(srcDir, dstDir, root, filename, keepDirectories)
Пример #17
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 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
Пример #19
0
def getNumber(text, default = 0, decimals = 3):
	gd = GenericDialog(text)
	gd.addNumericField(text, default, decimals)  # show 6 decimals
	gd.showDialog()
	if gd.wasCanceled():
		IJ.log('User canceled dialog!')
		return
	return gd.getNextNumber()
Пример #20
0
def getName(text, defaultName = ''):
	gd = GenericDialog(text)
	gd.addStringField(text, defaultName)
	gd.showDialog()
	if gd.wasCanceled():
		print 'User canceled dialog!'
		return
	return gd.getNextString()
Пример #21
0
def getRefChannel(channels, text = 'Reference Channel'): #dialog prompt to choose the reference channel
	gd = GenericDialog(text)
	gd.addChoice("output as", channels, channels[0])
	gd.showDialog()
	if gd.wasCanceled():
		print "User canceled dialog!"
		return
	return gd.getNextChoice()
Пример #22
0
def run():
    srcDir = IJ.getDirectory("Input_directory")
    if not srcDir:
        return
    gd = GenericDialog("Do you want to run the image correction now?")
    gd.showDialog()
    if gd.wasCanceled():
        return
    find_folders(srcDir)
Пример #23
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 _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
Пример #25
0
def choose_analysis_mode(params):
    """present UI for choosing how cells should be identified"""
    dialog = GenericDialog("Analysis methods")
    dialog.addMessage("Please choose how cell shape anlaysis should proceed:")
    dialog.addChoice("Analysis mode", params.list_analysis_modes(),
                     params.last_analysis_mode)
    dialog.showDialog()
    if dialog.wasCanceled():
        raise KeyboardInterrupt("Run canceled")
    return dialog.getNextChoice()
def getOptions():
	gd = GenericDialog("Option")
	gd.addNumericField("Sliding Z Projection Slices", 5, 0) # show 0 decimals
	gd.addHelp("http://www.robertcudmore.org/software/bSliding_Z_Projection.html")
	gd.showDialog()

	if gd.wasCanceled():
		print "User cancelled dialog."
		return
	#read out options
	userSlices = gd.getNextNumber()
	return int(userSlices)
Пример #27
0
def getMinMaxFor8Bit(minMaxs):
	gd = GenericDialog('Enter the min and max for each channel for the 8 bit transformation')
	for channel in minMaxs.keys():
		gd.addNumericField('Min ' + channel , minMaxs[channel][0], 2) # show 2 decimals
		gd.addNumericField('Max ' + channel, minMaxs[channel][1], 2)
	gd.showDialog()
	if gd.wasCanceled():
		IJ.log('User canceled dialog!')
		return
	for channel in minMaxs.keys():
		minMaxs[channel][0] = gd.getNextNumber()
		minMaxs[channel][1] = gd.getNextNumber()
	return minMaxs
def warning_dialog(message):
	"""show a warning dialog with a user-defined message"""
	dialog = GenericDialog("Warning!");
	dialog.setCancelLabel("Cancel analysis");
	if type(message) is list:
		for line in message:
			dialog.addMessage(line);
	else:
		dialog.addMessage(message);
	dialog.showDialog();
	if dialog.wasCanceled():
		raise KeyboardInterrupt("Run canceled");
	return;
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():
	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
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]
Пример #32
0
def create_selection_dialog(image_titles, defaults, title='Select images for processing'):
    gd = GenericDialog(title)
    # The build in function enumerate() returns two values:
    # The index and the value stored in the tuple/list.
    for index, default in enumerate(defaults):
        # for each loop we add a new choice element to the dialog.
        gd.addChoice('Image_'+ str(index + 1), image_titles, image_titles[default])
    gd.showDialog()
    if gd.wasCanceled():
        return None
    # This function returns a list.
    # _ is used as a placeholder for values we don't use.
    # The for loop is used to call gd.getNextChoiceIndex() len(defaults) times.
    return [gd.getNextChoiceIndex() for _ in defaults]
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")
Пример #34
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
Пример #35
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
Пример #36
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]
Пример #37
0
def getOptions(imp):
  gd = GenericDialog("Correct 3D Drift Options")
  channels = []
  for ch in range(1, imp.getNChannels()+1 ):
    channels.append(str(ch))
  gd.addMessage("Select a channel to be used for the registration.")
  gd.addChoice("     channel:", channels, channels[0])
  gd.addCheckbox("Use virtualstack?", False)
  gd.addMessage("This will store the registered hyperstack as an image sequence and\nshould be used if free RAM is less than 2X the size of the hyperstack. ")
  gd.showDialog()
  if gd.wasCanceled():
    return
  channel = gd.getNextChoiceIndex() + 1  # zero-based
  virtual = gd.getNextBoolean()
  return channel, virtual
Пример #38
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
def getOptions():

    pixels = zeros('f', 4)  # 4 elements

    # First Dialog Box
    item = [
        "coralline", "tunicate", "red", "macro", "background", "more than one"
    ]
    gd = GenericDialog("Options")
    gd.addRadioButtonGroup("options", item, 3, 2, "coralline")
    gd.showDialog()
    button = gd.getNextRadioButton()

    # Second Dialog Box
    gd2 = GenericDialog("Multiple Options")
    items = ["coralline", "tunicate", "red", "macro", "garbage"]
    defaultVal = [False] * 5
    gd2.addCheckboxGroup(2, 3, items, defaultVal)
    gd2.addNumericField("coralline %", 0, 0)
    gd2.addNumericField("tunicate %", 0, 0)
    gd2.addNumericField("red %", 0, 0)
    gd2.addNumericField("macro %", 0, 0)
    gd2.addNumericField("background %", 0, 0)

    if gd.wasCanceled():
        return 0

    if button == "coralline":
        pixels[0] = 1
    elif button == "tunicate":
        pixels[1] = 1
    elif button == "red":
        pixels[2] = 1
    elif button == "macro":
        pixels[3] = 1
    elif button == "more than one":
        gd2.showDialog()
        checklist = gd2.getCheckboxes()
        pixels[0] = int(
            checklist[0].state) * (float(gd2.getNextNumber()) / 100)
        pixels[1] = int(
            checklist[1].state) * (float(gd2.getNextNumber()) / 100)
        pixels[2] = int(
            checklist[2].state) * (float(gd2.getNextNumber()) / 100)
        pixels[3] = int(
            checklist[3].state) * (float(gd2.getNextNumber()) / 100)

    return pixels
Пример #40
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
Пример #41
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  
Пример #42
0
def pixel_resolution_dialog(pixel_width=None, frame_interval=None):
    if pixel_width is None:
        pixel_width = 1
    if frame_interval is None:
        frame_interval = 1

    gd = GenericDialog("Specify image resolution")
    gd.addNumericField("Pixel width (microns): ", pixel_width, 4)
    gd.addNumericField("Frame interval (seconds): ", frame_interval, 4)

    gd.showDialog()
    if gd.wasCanceled():
        return

    pixel_width = gd.getNextNumber()
    frame_interval = gd.getNextNumber()
    return pixel_width, frame_interval
Пример #43
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
Пример #44
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
Пример #45
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 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
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()
    
Пример #49
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
Пример #50
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
Пример #51
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()
Пример #52
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
Пример #53
0
def open_Octopus_file():

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

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

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

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

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

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

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

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

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

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

	# sort the file numbers
	sorted_filenums = sorted(filenums)

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


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

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

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

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

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

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

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

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

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

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

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


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

		else:
			break

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

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

	return True
Пример #54
0
from ij.gui import GenericDialog

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

gd = GenericDialog('About CMTK')
gd.addMessage('CMTK Registration suite is open source software released under GPLv3',)
gd.addMessage('Currently installed CMTK version: '+cmtkgui.installed_version())
gd.addMessage('CMTK binary directory: '+cmtkgui.bin_dir())
gd.setCancelLabel("CMTK Web Page")
gd.showDialog()
if gd.wasCanceled():
	from ij import IJ
	IJ.runPlugIn("ij.plugin.BrowserLauncher", "http://www.nitrc.org/projects/cmtk/")
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)
Пример #56
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()
Пример #57
0
def Options(sourceFolder):
	#globals
	global gFileType
	global gGetNumChanFromScanImage
	global gNumChannels
		
	global gDoAlign
	global gAlignThisChannel
	
	global gDoCrop
	global gCropLeft
	global gCropTop
	global gCropWidth
	global gCropHeight
	
	global gAlignOnMiddleSlice
	global gAlignOnThisSlice
	global gRemoveCalibration
	global gLinearShift
	global gSave8bit

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

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

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

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

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

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

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

		gLinearShift = int(gd.getNextNumber())

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

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

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

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

		# print to fiji console
		bPrintLog('These are your global options:', 0)
		bPrintLog('gFileType=' + gFileType, 1)
		bPrintLog('gGetNumChanFromScanImage=' + str(gGetNumChanFromScanImage), 1)
		bPrintLog('gNumChannels=' + str(gNumChannels), 1)
		bPrintLog('gRemoveCalibration=' + str(gRemoveCalibration), 1)
		bPrintLog('gLinearShift=' + str(gLinearShift), 1)
		bPrintLog('gDoCrop=' + str(gDoCrop), 1)
		bPrintLog('gDoAlign=' + str(gDoAlign), 1)
		bPrintLog('gAlignThisChannel=' + str(gAlignThisChannel), 1)
		bPrintLog('gSave8bit=' + str(gSave8bit), 1)
		
		return 1