Пример #1
0
def user_input():
	""" Takes user input on experiment parameters and stimulation applications... """
	
	User_Input_List = []
	Stim_List = []
	
	# Creates dialog boxes proportionally to number of stimulations, type and duration. 
  	if Stim_num >= 1:
  		gd = GenericDialog("Stimulation applications")
  		for stim in range(0, Stim_num, 1):
  			gd.addStringField("Stimulation type "+str(stim+1)+":", "cLTP")
  			gd.addNumericField("Stimulation start:", stim*2, 2)
  			gd.addNumericField("Stimulation end:", (stim+1)*2, 2)
  		
  		gd.showDialog()

  	# Lists the different stimulations.
	for stim in range(0, Stim_num, 1):
		Type_Stim = gd.getNextString()
  		Start_Stim = gd.getNextNumber()
  		End_Stim = gd.getNextNumber()
  		Stim_List.append([Type_Stim, float(Start_Stim), float(End_Stim)])

	User_Input_List.extend(Stim_List)
	
	# Creates a dictionary of all user inputs.
	User_Input_Dict = {'Parameters': User_Input_List[0]}
	for stim in range(1, Stim_num, 1):
		User_Input_Dict['Stimulation '+str(stim)] = User_Input_List[stim]

	# Dumps dict to JSON.	
	User_Input_Dict_JSON = (json.dumps(User_Input_Dict))	
	return User_Input_Dict, User_Input_Dict_JSON, Stim_List
Пример #2
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
Пример #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
Пример #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
	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
Пример #7
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
Пример #8
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()
def getPixel(
):  # Get pixel size from user with dialog box. could return python dict or make custom class? Note user can return a NaN if doesnt enter numeric
    gd = GenericDialog("Pixel")
    gd.addNumericField("Pixel size desired (mm)", 6.4,
                       1)  # default is 1 decimal
    gd.showDialog()
    Pixel_size = gd.getNextNumber(
    )  #6.4 # ENTER mm, remember tolerance is +/-30%
    return Pixel_size
def 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)
Пример #11
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
Пример #12
0
def get_opts():
	gd = GenericDialog("setup plugin")
	#channels = map(lambda x: str(x), range(1,imp.getNChannels()+1))
	channels = ['1','2','3'];
	modes = ['batch mode', 'manual']
	gd.addChoice("processing mode",modes,modes[1])
	gd.addChoice("choose channel for pre-registration: ", channels, channels[0])
	gd.addChoice("choose channel for registration: ", channels, channels[2])
	gd.addChoice("channel for cell detection: ", channels, channels[1])
	gd.addChoice("channel for osteoblast detection: ", channels, channels[2])
	gd.addChoice("channel for vasculature detection: ", channels, channels[0])
#	gd.addNumericField("quantile for cell segmentation", 0.9995, 36)
	gd.addNumericField("rough cell size in microns", 15., 2)
#	gd.addSlider("minimal z depth (voxels) for detected cells", 1, imp.getNSlices()+1, 8)
	gd.addSlider("minimal z depth (voxels) for detected cells", 1,36, 5)
	gd.addSlider("minimal z depth (voxels) for detected cells", 1,36, 25)

	gd.addCheckbox("delete black frames (recommended)", True)
	gd.addChoice("channel to estimate black frames: ", channels, channels[2])
	gd.addCheckbox("rough registration of time series", True)
	gd.addCheckbox("descriptor-based registration of time series", True)
	gd.addCheckbox("detect cells", False)
	gd.addCheckbox("export osteoblast structures", False)
	gd.addCheckbox("export vasculature structures", False)
	gd.addCheckbox("save registered movie", True)
	gd.addCheckbox("delete temporary files", True)
	#gd.addCheckbox("show 3d vis", False)

	gd.showDialog()
	proc_mode = gd.getNextChoice()
	ch_pre = gd.getNextChoice()
	reg = gd.getNextChoice()
	cc = gd.getNextChoice()
	ost_ch = gd.getNextChoice()
	vasc_ch = gd.getNextChoice()
	#quantile = gd.getNextNumber()
	size = gd.getNextNumber()
	minz = gd.getNextNumber()
	zmax = gd.getNextNumber()
	del_black = gd.getNextBoolean();
	black_ch = gd.getNextChoice()
	preregflag = gd.getNextBoolean();
	regflag = gd.getNextBoolean()
	detect_cells = gd.getNextBoolean()
	struct_exp = gd.getNextBoolean()
	vasc_exp = gd.getNextBoolean()
	save_res = gd.getNextBoolean()
	del_tmp = gd.getNextBoolean()
	#vis = gd.getNextBoolean()

	return proc_mode, ch_pre, reg, cc, ost_ch, vasc_ch, size, minz, zmax, del_black, black_ch, preregflag, regflag, detect_cells, struct_exp, vasc_exp, save_res, del_tmp
Пример #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 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      
Пример #15
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
Пример #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 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
Пример #19
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
Пример #20
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
Пример #21
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
Пример #22
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
Пример #23
0
def get_options():
    """ Get user options. """

    gd = GenericDialog("Options")
    gd.addCheckbox("3x3 boundary region", True)
    gd.addCheckbox("5x5 boundary region", True)
    # change the multiple of the standard deviation that is used
    # as a cutoff for the subtraction
    gd.addNumericField("N * sigma cutoff", 3.00, 2)  # 2 decimals
    gd.showDialog()
    # check if user canceled operation
    if gd.wasCanceled():
        return
    # pull options
    close = gd.getNextBoolean()
    far = gd.getNextBoolean()
    cutoff = gd.getNextNumber()
    return close, far, cutoff
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
Пример #25
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 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 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)
Пример #28
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.addMessage("")
    dialog.addChoice("GFP segmentation method: ", AutoThresholder.getMethods(),
                     params.last_threshold_method)
    dialog.addNumericField("Minimum cell area (um" + _squared + "): ",
                           params.last_minimum_cell_area_um2, 0)
    # dl = AnalysisModeListener()
    # dialog.addDialogListener(dl)
    dialog.showDialog()
    if dialog.wasCanceled():
        print("Run canceled")
        return None, None, None
    return dialog.getNextChoice(), dialog.getNextChoice(
    ), dialog.getNextNumber()
Пример #29
0
def getOptions():
	gd = GenericDialog("Options")
	gd.addNumericField("Channel_1", 2, 0)
	gd.addNumericField("Channel_2", 4, 0)
	gd.addNumericField("radius_background", 40, 0)
 	gd.addNumericField("sigmaSmaller", 3, 0)
 	gd.addNumericField("sigmaLarger", 15, 0)
  	gd.addNumericField("minPeakValue", 500, 0)
  	gd.addNumericField("min_dist", 20, 0)
  	gd.showDialog()
	Channel_1 = gd.getNextNumber()
	Channel_2 = gd.getNextNumber()
	radius_background = gd.getNextNumber()
  	sigmaSmaller = gd.getNextNumber()
  	sigmaLarger = gd.getNextNumber()
  	minPeakValue = gd.getNextNumber()
  	min_dist = gd.getNextNumber()

  	return int(Channel_1), int(Channel_2), radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist
def getOptions():
    gd = GenericDialog("Options")
    gd.addStringField("name", "Untitled")
    gd.addNumericField("alpha", 0.25, 2)  # show 2 decimals
    gd.addCheckbox("optimize", True)
    types = ["8-bit", "16-bit", "32-bit"]
    gd.addChoice("output as", types, types[2])
    gd.addSlider("scale", 1, 100, 100)
    gd.showDialog()
    #
    if gd.wasCanceled():
        print "User canceled dialog!"
        return
    # Read out the options
    name = gd.getNextString()
    alpha = gd.getNextNumber()
    optimize = gd.getNextBoolean()
    output = gd.getNextChoice()
    scale = gd.getNextNumber()
    return name, alpha, optimize, output, scale
Пример #31
0
def getOptions():  
  gd = GenericDialog("Loci Distance to compartment option")  
 
  gd.addChoice("Compartment Channel", ["1","2","3","4"], "1")
  gd.addNumericField("Compartment Threshold",0.60,2)
  gd.addChoice("Loci Channel", ["1","2","3","4"], "2")
  gd.addNumericField("Compartment Threshold",0.60,2)
  gd.showDialog()  
  #  
  if gd.wasCanceled():  
    print "User canceled dialog!"  
    return  
#  # Read out the options  
 
  speck_ch= int(gd.getNextChoice())
  speck_th = gd.getNextNumber() 
  loci_ch= int(gd.getNextChoice())
  loci_th = gd.getNextNumber()
  
  return speck_ch,speck_th, loci_ch, loci_th
#
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()
    
def showDialogR(R, val):
    """ Create dialog for input and save R values in settings
	"""
    gui = GenericDialog("Heterogeneous Z Correction")
    msg = "Heterogeneous Z Correction calculates an optical model\n"\
       "based on rational fluorescence intensity attenuation\n"\
       "over depth, in the form of (ax+b)/(x+c). Please specify\n"\
       "(a,b,c) for each region. You should provide a z-stack with\n"\
       "unique pixel values for each region.\n"
    gui.addMessage(msg)
    for ii in range(len(val)):
        gui.addNumericField(
            "Region " + str(ii) + " (" + str(val[ii]) + "):   a", R[ii][0], 2)
        gui.addToSameRow()
        gui.addNumericField("b", R[ii][1], 2)
        gui.addToSameRow()
        gui.addNumericField("c", R[ii][2], 2)
    gui.addHelp(
        r"https://github.com/alexandrebastien/heterogeneous-z-correction")
    gui.showDialog()
    if gui.wasOKed():
        R = []
        for ii in range(len(val)):
            R = R + [
                (gui.getNextNumber(), gui.getNextNumber(), gui.getNextNumber())
            ]
        Prefs.set("HetZCorr.R", str(R))
        return R
    else:
        return
Пример #34
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
Пример #35
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())
Пример #36
0
def getOptions():
	"""TODO: Put function docstring here.
	"""
	
	gd = GenericDialog('Gaussian 2D Window')
	gd.addMessage('Input options:')
	gd.addMessage('Gaussian window width in pixels.\nValue must be >= 3 pixels.')
	gd.addNumericField('width', 3.0, 0, 5, 'pixels')
	gd.addMessage('Gaussian window height in pixels.\nValue must be >= 3 pixels.')
	gd.addNumericField('height', 3.0, 0, 5, 'pixels')
	gd.addMessage('Standard deviation in the x direction\nas precentage of window width.')
	gd.addNumericField('sigma x', 0.33, 2, 5, '%')
	gd.addMessage('Standard deviation in the y direction\nas precentage of window width.')
	gd.addNumericField('sigma y', 0.33, 2, 5, '%') 
	gd.showDialog()

	# Handle if user hits the 'Cancel' button.
	if gd.wasCanceled():
		return None

	# Validate and collect the user input data.
	width = gd.getNextNumber()
	if width < 3.0:
		width = 3.0
	height = gd.getNextNumber()
	if height < 3.0:
		height = 3.0
	sigma_x = gd.getNextNumber()
	if sigma_x < 0.0:
		sigma_x = 0.0
	if sigma_x > 1.0:
		sigma_x = 1.0
	sigma_y = gd.getNextNumber()
	if sigma_y < 0.0:
		sigma_y = 0.0
	if sigma_y > 1.0:
		sigma_y = 1.0
	
	return InputOptions(
		width=int(width),
		height=int(height),
		sigma_x=float(sigma_x),
		sigma_y=float(sigma_y)
		)
Пример #37
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  
Пример #38
0
def getSegmentationParameters():
    gd = GenericDialog('Enter segmentation parameters')
    gd.addMessage(
        'Slice selection thresholds (percentiles of average intensity): \n \n')
    gd.addNumericField('Lower threshold', 0.25, 2)
    gd.addNumericField('Upper threshold', 0.65, 2)
    gd.addMessage('Image processing parameters for cells: \n \n')
    gd.addNumericField('Width of Gaussian filter [px]', 4, 0)
    gd.addChoice('Auto threshold method', [
        'Huang', 'Huang2', 'Intermodes', 'IsoData', 'Li', 'MaxEntropy', 'Mean',
        'MinError(I)', 'Minimum', 'Moments', 'Otsu', 'Percentile',
        'RenyiEntropy', 'Shanbhag', 'Triangle', 'Yen'
    ], 'Triangle')
    gd.addStringField('Particle size range [px^2]', '10000-5000000', 16)
    gd.addStringField('Particle circularity range', '0.20-1.00')
    gd.addMessage('Image processing parameters for nuclei: \n \n')
    gd.addNumericField('Width of Gaussian filter [px]', 4, 0)
    gd.addChoice('Auto threshold method', [
        'Huang', 'Huang2', 'Intermodes', 'IsoData', 'Li', 'MaxEntropy', 'Mean',
        'MinError(I)', 'Minimum', 'Moments', 'Otsu', 'Percentile',
        'RenyiEntropy', 'Shanbhag', 'Triangle', 'Yen'
    ], 'Otsu')
    gd.addStringField('Particle size range [px^2]', '3500-10000', 16)
    gd.addStringField('Particle circularity range', '0.5-1.00')
    gd.addCheckbox('Run in testing mode?', 0)
    gd.showDialog()
    if gd.wasCanceled():
        print 'User canceled dialog!'


# Read out inputs
    params = {}
    params['avgI_low'] = gd.getNextNumber()
    params['avgI_high'] = gd.getNextNumber()
    params['cellsigma'] = int(gd.getNextNumber())
    params['cellmethod'] = gd.getNextChoice()
    params['cellsize'] = gd.getNextString()
    params['cellcircularity'] = gd.getNextString()
    params['nucsigma'] = int(gd.getNextNumber())
    params['nucmethod'] = gd.getNextChoice()
    params['nucsize'] = gd.getNextString()
    params['nuccircularity'] = gd.getNextString()
    params['test'] = gd.getNextBoolean()
    return params
Пример #39
0
def runGUI():

    defaultRad = 20
    defaultNCols = 20
    defaultNRows = 5

    gd = GenericDialog("Blobber - v0.1 alpha")
    gd.addMessage(
        "\tBlobber is a generic spot array analyzer \n\t\t\t\t\t\t\t\t\t\t\t\t\t(copyright Artur Yakimovich 2019)\n\n"
    )

    gd.addNumericField("Number_of_columns", defaultNCols, 0)
    gd.addNumericField("Number_of_rows", defaultNRows, 0)
    gd.addNumericField("Circle_radius_(px)", defaultRad, 0)
    nCols = int(gd.getNextNumber())
    nRows = int(gd.getNextNumber())
    rad = int(gd.getNextNumber())
    gd.showDialog()
    if gd.wasCanceled():
        return None
    runScript(nCols, nRows, rad)
	# Copies tiles for stitching into temp directory and stitches, if necessary
	if len(tiles)==1:
		params = "open=["+ imgDir +"tile_"+str(tiles[0])+".ome.tif] color_mode=Default view=Hyperstack stack_order=XYCZT"
		IJ.run("Bio-Formats Importer", params);
		tileImage = WindowManager.getImage("tile_"+str(tiles[0])+".ome.tif")
		tileImage.setSlice(int(tileImage.getNSlices()/2))
	else:
		ind = 1
		tileDiskSize = os.path.getsize(imgDir+"tile_"+str(tiles[0])+".ome.tif")
		totalDiskSize = tileDiskSize * len(tiles)
		totalDiskSizeMB = totalDiskSize / 1048576
		sizeGD = GenericDialog("Warning")
		sizeGD.addMessage("Memory used by selected tiles is " + str(totalDiskSizeMB) + "MB. Continue?")
		sizeGD.addCheckbox("Compute overlap",False)
		sizeGD.addNumericField("Tile overlap percentage",10,0)
		sizeGD.addCheckbox("Write fused image sequence to disk",False)
		sizeGD.showDialog()
		doComputeOverlap = sizeGD.getNextBoolean()
		overlapPctStr = str(sizeGD.getNextNumber())
		doWriteToDisk = sizeGD.getNextBoolean()
		if (doComputeOverlap):
			overlapText = "compute_overlap ignore_z_stage"
		else:
			overlapText = ""
		if (doWriteToDisk):
			outputPath = imgDir + "substitched"
			diskWriteText = "image_output=[Write to disk] output_directory=[" + outputPath + "]"
		else:
			diskWriteText = "image_output=[Fuse and display]"
		if (sizeGD.wasOKed()):
from ij import IJ
from ij.gui import GenericDialog

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

values = gd.getNumericFields();
for val in values:
	IJ.log(val.text)
from ij import IJ
from ij.gui import GenericDialog
from ij.plugin import ChannelSplitter
from ij.plugin import RGBStackMerge
from ij.plugin import ImageCalculator
from ij import WindowManager

theImage = IJ.getImage()
gd = GenericDialog("Options...")
channelText = [("Channel " + str(ch+1)) for ch in range(theImage.getNChannels())]
gd.addChoice("Amplified_channel",channelText,channelText[0])
gd.addChoice("Reference_channel",channelText,channelText[-1])
gd.addNumericField("Amplifying_ratio",1,0)
gd.addCheckbox("Remove_bleedthrough",True)
gd.addCheckbox("Correct_for_refraction",True)
gd.showDialog()
if gd.wasOKed():
	amplifyChannel = gd.getNextChoiceIndex() + 1
	refChannel = gd.getNextChoiceIndex() + 1
	ampFactor = gd.getNextNumber()
	doRemoveBleedthrough = gd.getNextBoolean()
	doCorrectRefraction = gd.getNextBoolean()
	chImages = ChannelSplitter.split(theImage)
	
	## After this step, the image to operate on is "nextStepImage"
	if doRemoveBleedthrough:
		params = ("bleeding_channel=" + str(refChannel) + " bloodied_channel=" + str(amplifyChannel) + " " +
				"allowable_saturation_percent=1.0 rsquare_threshold=0.50")
		IJ.run("Remove Bleedthrough (automatic)", params)
		unbledImage = WindowManager.getImage("Corrected_ch" + str(amplifyChannel))
		mergingImages = [unbledImage,chImages[refChannel-1].duplicate()]
Пример #43
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
Пример #44
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()
Пример #45
0
dc = DirectoryChooser("Choose directory with OME.TIF files...")
sourceDir = dc.getDirectory()

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

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

	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Sizing_ratio (Final disk space / Initial disk space):",0.25,2)
	gd.addMessage("Directory size: " + str(dirSizeMB) + "MB")
	gd.addMessage("Maximum memory: " + str(memFijiMB) + "MB")
	mem_recs = calculate_memory_recs(dirSize,memFiji)
	print mem_recs
	for i in range(0,len(mem_recs)):
		ratio_rec = float(mem_recs[i]) / dirSizeMB
		if (ratio_rec > 1):
			ratio_rec = 1
		print ratio_rec
		ratio_rec_str = "%.3f" % ratio_rec
		gd.addMessage(str(i+1)+"-channel: " + str(mem_recs[i]) + "MB; Ratio: " + ratio_rec_str)
	gd.showDialog()
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
			if Verbose:
				IJ.log('... ' + str(xpos) + ', ' + str(ypos) + ', ' + str(zpos))
			outimp.getStack().getProcessor(int(zpos)+1).putPixel(int(xpos), int(ypos), i+1)
	return outimp
	
Verbose = False
if IJ.isMacro():
    opt = getArgument()# ImageJ specific function Macro.getOptions()
    if len(opt) == 0:
        opt = OPT_PLACEHOLDER
    IJ.log(opt)
    optA = opt.split()
    Number_of_Cluster = int(optA[0])
    Iteration = int(optA[1])
else:
   gd =  GenericDialog("KMean Points Clustering", IJ.getInstance())
   gd.addNumericField("Expected Number of Clusters", 4, 0)
   gd.addNumericField("Iterations", 10, 0)
   gd.showDialog()
   Number_of_Cluster = int(gd.getNextNumber())
   Iteration = int(gd.getNextNumber())
imp = IJ.getImage()
outimp = core(imp)
outimp.show()
IJ.run(outimp, "glasbey inverted", "")
		



	


    t0 = time.time()
    print t0 - t0

    imgSource = IJ.getImage()

    root   = '/tier2/saalfeld/hanslovskyp/shan/thickness/'
    c      = imgSource.getWidth()/2
    height = imgSource.getHeight()

    dialog = GenericDialog( "Overlapping thickness estimation" )
    dialog.addStringField( "Root directory for storing results", root )
    dialog.addCheckbox( "Render matrix to image at each iteration.", False )
    dialog.addNumericField( "Start.", 0, 0 )
    dialog.addNumericField( "Stop.", height, 0 )
    dialog.addNumericField( "Interval size.", 1000, 0 )
    dialog.addNumericField( "Overlap.", imgSource.getWidth()/2, 0 )
    dialog.addNumericField( "Range.", c, 0 )

    dialog.showDialog()

    if dialog.wasCanceled():
        raise Exception( "dialog was canceled" )

    root     = dialog.getNextString()
    doRender = dialog.getNextBoolean()
    start    = dialog.getNextNumber()
    stop     = dialog.getNextNumber()
    interval = dialog.getNextNumber()
          IJ.run("Bio-Formats Importer", cmd);
          imp = IJ.getImage()
          analyse(imp, root, filename, thresholds)
        else: 
          imp = Opener().openImage(root, filename)
          analyse(imp, root, filename, thresholds)
        
          
if __name__ == '__main__':
  srcDir = DirectoryChooser("Choose directory").getDirectory()
  #od = OpenDialog("Click on one of the image files in the folder to be analysed", None	)
  #filename = od.getFileName()
  #foldername = od.getDirectory()
  #foldername = "Z:/Tischi/projects/CellZome/2015-04-27--3D_Tissue/data"
  gd = GenericDialog("3D Tissue analysis");
  gd.addNumericField("Threshold Nuclei: ", 4000, 0);
  gd.addNumericField("Threshold Ch2: ", 1000, 0);
  gd.addNumericField("Threshold Dots: ", 3000, 0);
  gd.addNumericField("x: ", 4000, 0);
  gd.addNumericField("y: ", 4000, 0);
  gd.addNumericField("width: ", 3000, 0);
  gd.addNumericField("height: ", 3000, 0);
  gd.showDialog();
  #if (gd.wasCanceled()):
  #  return
  thresholds = []
  thresholds.append(gd.getNextNumber())
  thresholds.append(gd.getNextNumber())
  thresholds.append(gd.getNextNumber())
  crop = []
  crop.append(gd.getNextNumber())
def getPixel():  # Get pixel size from user with dialog box. could return python dict or make custom class? Note user can return a NaN if doesnt enter numeric
	gd = GenericDialog("Pixel")
	gd.addNumericField("Pixel size desired (mm)", 6.4, 1) # default is 1 decimal
	gd.showDialog()
	Pixel_size = gd.getNextNumber()	#6.4 # ENTER mm, remember tolerance is +/-30%
	return Pixel_size
        print "\nwill not analyze file:",filename
        continue
      else:
        #print root
        print "\nanalyzing file:",filename
        imp = Opener().openImage(root, filename)
        analyse(imp, root, filename, thresholds)

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

	return(theObjects[min_ind])

## Main body of script
## Gets the channel to work on
opener = OpenDialog("Select parent LSM file...")
parentLSMFilePath = opener.getPath()
if (parentLSMFilePath is not None):
	stackInfo = parse_tile_info_file(parentLSMFilePath + "_tiles/tile_info.txt")
	channelTexts = map(lambda x: str(x), filter(lambda x:os.path.isfile(parentLSMFilePath+"_tiles/objects/C"+str(x)+"-tile_1.csv"),range(1,stackInfo[0]+1)))
	gd = GenericDialog("Specify parameters...")
	gd.addChoice("Which_channel",channelTexts,channelTexts[0])
	gd.addNumericField("Linear_pixel_num",512,0)
	gd.showDialog()
	if gd.wasOKed():
		channel = int(gd.getNextChoice())
		pixelLimit = int(gd.getNextNumber())

		## Obtains global coordinate system for tiles
		scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif")
		coords = read_tileconfig_file(parentLSMFilePath+"_tiles/resized/TileConfiguration.registered.txt")
		upscaled_coords = normalize_coords_in_dict(upscale_coords(coords,scale_info[0]))
		#print upscaled_coords

		## Parses each of the object files and converts coordinates to global coordinates
		objectDB = [[] for i in range(stackInfo[1])]
		filteredObjectDB = [[] for i in range(stackInfo[1])]
		duplicatedObjectDB = [[] for i in range(stackInfo[1])]
from ij import IJ
from ij.gui import GenericDialog
from ij import ImageStack
from ij import ImagePlus

theImage = IJ.getImage()

gd = GenericDialog("Expand stack...")
gd.addNumericField("Multiple (natural number):",4,0)
gd.showDialog()

if (gd.wasOKed()):
	newStack = ImageStack(theImage.getWidth(),theImage.getHeight())
	multiple = int(gd.getNextNumber())

	for i in range(1,theImage.getNSlices()):
		theImage.setSlice(i)
		ip = theImage.getProcessor()
		for j in range(multiple):
			newip = ip.duplicate()
			newStack.addSlice(newip)

	resultImage = ImagePlus("stack_exp",newStack)
	resultImage.show()
	al2.measure()
	al2.displayResults()
	image1.deleteRoi()
	image2.deleteRoi()

	val_high = rt.getValueAsDouble(1,0)
	val_bleed = rt.getValueAsDouble(1,1)
	val_low = rt.getValueAsDouble(1,2)
	val_zero = rt.getValueAsDouble(1,3)
	val_target = val_high - val_low
#	scale_target = val_target / val_bleed
	scale_target = val_target / (val_bleed - val_zero)
	print scale_target

	gd = GenericDialog("Scale factor")
	gd.addNumericField("Scale factor on subtraction:",scale_target,3)
	gd.showDialog()

	if (gd.wasCanceled()): 
		quit()

	scale = gd.getNextNumber()

	tempImage = image2.duplicate()
	for i in range(tempImage.getNSlices()):
		tempImage.setSliceWithoutUpdate(i+1)
		ip = tempImage.getProcessor()
		ip.subtract(val_zero)
		ip.multiply(scale)
	ic = ImageCalculator()
	newImage = ic.run("Subtract create stack",image1,tempImage)
Пример #54
0
from ij.gui import GenericDialog
from ij import IJ

theImage = IJ.getImage()

gd = GenericDialog("Set grid size")
gd.addNumericField("Number of rows:",10,0)
gd.addNumericField("Number of columns:",10,0)
gd.showDialog()
if (gd.wasOKed()):
	IJ.run("Colors...","foreground=cyan background=cyan selection=yellow")
	numRows = gd.getNextNumber()
	numCols = gd.getNextNumber()
	colDim = theImage.getWidth() / (numCols)
	rowDim = theImage.getHeight() / (numRows)
	rowStarts = range(rowDim,theImage.getHeight()-numRows,rowDim)
	colStarts = range(colDim,theImage.getWidth()-numCols,colDim)
	rowCenters = list(rowStarts)
	rowCenters.insert(0,0)
	colCenters = list(colStarts)
	colCenters.insert(0,0)
	for i in range(0,len(rowCenters)):
		rowCenters[i] = rowCenters[i] + rowDim - rowDim/8
	for i in range(0,len(colCenters)):
		colCenters[i] = colCenters[i] + colDim/2

	for i in rowStarts:
		IJ.makeLine(0,i,theImage.getWidth(),i)
		IJ.run("Draw","stack")
	for i in colStarts:
		IJ.makeLine(i,0,i,theImage.getHeight())
Пример #55
0
dc = DirectoryChooser("Choose directory with OME.TIF files...")
sourceDir = dc.getDirectory()

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

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

	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Final disk space / Initial disk space:",0.25,2)
	gd.addMessage("Directory size: " + str(dirSizeMB) + "MB")
	gd.addMessage("Maximum memory: " + str(memFijiMB) + "MB")
	mem_recs = calculate_memory_recs(dirSize,memFiji)
	print mem_recs
	for i in range(0,len(mem_recs)):
		ratio_rec = float(mem_recs[i]) / dirSizeMB
		if (ratio_rec > 1):
			ratio_rec = 1
		print ratio_rec
		ratio_rec_str = "%.3f" % ratio_rec
		gd.addMessage(str(i+1)+"-channel: " + str(mem_recs[i]) + "MB; Ratio: " + ratio_rec_str)
	gd.showDialog()
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
# Gets the input LSM image
theOpenDialog = OpenDialog("Choose large LSM file to open...")
theFilePath = theOpenDialog.getPath()
if not(theFilePath is None):
	theDirectory = theOpenDialog.getDirectory()
	theFileName = theOpenDialog.getFileName()
	baseName = os.path.splitext(theFileName)[0]
		
	# Creates the output directory
	if not os.path.exists(theDirectory + baseName + "_resized"):
		os.mkdir(theDirectory + baseName + "_resized")

	# Asks for parameters
	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Start tile:",1,0)
	gd.addNumericField("Finish tile:",9,0)
	gd.addNumericField("Final disk space / Initial disk space:",0.25,2)
	gd.addNumericField("Step size (higher is faster but uses more memory):",10,0)
	gd.showDialog()
	startTile = int(gd.getNextNumber())
	finishTile = int(gd.getNextNumber())
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
	stepSize = int(gd.getNextNumber())
	
	# Performs scaling
	if (gd.wasOKed()):
		anchorTiles = range(startTile,finishTile+1,stepSize)
		print anchorTiles
		for i in anchorTiles:
Пример #57
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