Exemple #1
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
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)
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
Exemple #4
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 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
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)
Exemple #7
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()
Exemple #8
0
def save_etc(imp, info, output_folder):
	"""handle saving output, final labelling and UI of what to do next"""
	dialog = GenericDialog("Marksl1 cell shape prescreen");
	dialog.addChoice("Vessel type: ", 
						info.get_vessel_types(), 
						info.get_vessel_type());
	dialog.addStringField("Channel 1 label: ", info.get_ch1_label());
	dialog.addStringField("Channel 2 label: ", info.get_ch2_label());
	dialog.addStringField("Experiment identifier: ", info.get_experiment_id());
	dialog.addStringField("Embryo identifier: ", info.get_embryo_id());
	dialog.setOKLabel("Save preprocessing");
	dialog.showDialog();
	info.set_vessel_type(dialog.getNextChoice());
	info.set_ch1_label(dialog.getNextString());
	info.set_ch2_label(dialog.getNextString());
	info.set_experiment_id(dialog.getNextString());
	info.set_embryo_id(dialog.getNextString());
	if dialog.wasCanceled():
		return "stop";
	if dialog.wasOKed():
		exsting_files = os.listdir(output_folder);
		r = re.compile(".*" + info.get_embryo_id() + " " + info.get_vessel_type() + ".*")
		fns = filter(r.match, exsting_files)
		numbers = list((int(s) for fn in fns for s in re.findall(r'\b\d+$', os.path.splitext(fn)[0])));
		append_digit = (max(numbers) + 1) if numbers else 1;
		ch1str = (info.get_ch1_label() + " ") if info.get_ch1_label() else "";
		ch2str = (info.get_ch2_label() + " ") if info.get_ch2_label() else "";
		expstr = (info.get_experiment_id() + " ") if info.get_experiment_id() else "";
		file_name = ("Cropped " + ch1str + ch2str + expstr + 
					"e" + str(info.get_embryo_id()) + " " + 
					info.get_vessel_type() + " " + 
					str(append_digit));
		FileSaver(imp).saveAsTiff(os.path.join(output_folder, (file_name + ".tif")));
		info.save_info_to_json(os.path.join(output_folder, (file_name + ".json")));
		continueDialog = YesNoCancelDialog(WM.getCurrentWindow(), 
											"Continue?", 
											"Continue with same input image or a new input image?", 
											"New image...", 
											"Same image");
		if continueDialog.cancelPressed():
			return "stop";
		if continueDialog.yesPressed():
			return "continue_newimage";
		return "continue_sameimage";
	return "stop";
Exemple #9
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
def findclearcell_run():
  inDir = IJ.getDirectory("Input directory")
  if not inDir:
    return
  gd = GenericDialog("Process Folder")
  gd.addStringField("File extension", ".oir")
  gd.addStringField("File name starts with (the date)", "")
  gd.showDialog()
  if gd.wasCanceled():
    return
  ext = gd.getNextString()
  containString = gd.getNextString()
  for root, directories, filenames in os.walk(inDir):
    for fileName in filenames:
      if not fileName.endswith(ext):
        continue
      if containString not in fileName:
        continue
      print findclearcell(inDir, root, fileName)
Exemple #11
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 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
Exemple #13
0
def getChannels(subFolder):
    gd = GenericDialog("Channel Options")

    gd.addStringField("Brain Region:", "")

    gd.addMessage("Name the markers associated with this directory:")
    gd.addMessage(inputDirectory + subFolder)
    gd.addMessage("(Leave empty to ignore)")
    gd.addMessage("")
    gd.addStringField("Channel 1:", "HEMO")
    gd.addStringField("Minimum size for Channel 1:", "20")
    gd.addStringField("Max size for Channel 1:", "500")

    gd.addMessage("")
    gd.addStringField("Channel 2:", "DAB")
    gd.addStringField("Minimum size for Channel 2:", "30")
    gd.addStringField("Minimum size for Channel 2:", "500")
    #	gd.addStringField("Channel 3:", "")

    gd.showDialog()

    channelNames = []

    region = gd.getNextString()

    channelNames.append([gd.getNextString(), 0])
    tooSmallHEMO = gd.getNextString()
    tooBigHEMO = gd.getNextString()
    channelNames.append([gd.getNextString(), 1])
    tooSmallDAB = gd.getNextString()
    tooBigDAB = gd.getNextString()

    #channelNames.append([gd.getNextString(), 2])

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

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

    return region, tooSmallHEMO, tooSmallDAB, tooBigHEMO, tooBigDAB, channels
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
#
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()
    
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ

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

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

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

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

	return returnVal
	

dc = DirectoryChooser("Choose root directory")
rootPath = dc.getDirectory()
if rootPath is not None:
	gd = GenericDialog("Batch mode options...")
	gd.addStringField("Filename extension","lsm",6)
	gd.showDialog()
	if (gd.wasOKed()):
		extension = gd.getNextString()
		for root, dirs, files in os.walk(rootPath):
			LSMfiles = filter(lambda x: check_if_filetype(x,extension),files)
			if len(LSMfiles)>0:
				LSMpaths = map(lambda x: generate_path(x,root),LSMfiles)
				explodeStatuses = map(run_explode,LSMpaths)
				resizePaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),LSMpaths,explodeStatuses)))
				if len(resizePaths)>0:
					resizeStatuses = map(run_resize,resizePaths)
					stitchPaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),resizePaths,resizeStatuses)))
					if len(stitchPaths)>0:
						stitchStatuses = map(run_stitch,stitchPaths)
						combinePaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),stitchPaths,stitchStatuses)))
						if len(combinePaths)>0:
							combineStatuses = map(run_combine,combinePaths)
					
Exemple #18
0
startTime = time.time()
imageCount = 0
voxel_info = str()

gd = GenericDialog("Set ToTiff Options")
gd.addStringField("File extension to be processed", ".nd2")
gd.addRadioButtonGroup("Output", outDirChoices, 3, 1, outDirChoices[0])
gd.addRadioButtonGroup("Overwrite", overwriteChoices, 2, 1, overwriteChoices[0])
gd.addRadioButtonGroup("Save channels in different subfolders", channelSubfolderChoices, 1, 1,
                       channelSubfolderChoices[0])
gd.addCheckboxGroup(2, 1, mipChoices, [False, False], ["Do you want maximum intensity projections of your images?"])
gd.showDialog()
if gd.wasCanceled():
    exit()

fileExt = gd.getNextString()
outDirPref = gd.getNextRadioButton()
overwritePref = gd.getNextRadioButton()
channelSubfolderPref = gd.getNextRadioButton()
mipPrefTIFF = gd.getNextBoolean()
mipPrefJPG = gd.getNextBoolean()

if not fileExt.startswith('.'):
    fileExt = '.' + fileExt

inDir = IJ.getDirectory("Choose Directory Containing Input Files")
if inDir is None:
    exit('No input directory selected!')

if outDirPref == outDirChoices[2]:
    outDir = inDir
Exemple #19
0
def run():
    types = [
        'oneDay', 'oneMouse', 'oneFile', 'oneMonth', 'OneFolder', 'mapManager'
    ]

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

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

            overWriteDate(dayFolder)

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

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

            runOneMonth(monthFolder)

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

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

            if len(mapFolders) == 0:
                bPrintLog('\nERROR: no map folder found', 0)
                return 0

            bPrintLog('Map Folder number: ' + str(len(mapFolders)), 0)
            #put option here so we do not have to click for each folder
            sourceFolders = [
                mapPath + '/' + mapFolder + '/raw/raw_userRaw'
                for mapFolder in mapFolders
            ]
            for srcFolder in sourceFolders:
                runOneFolder(srcFolder)

# User input directory
directory = IJ.getDirectory("Input_directory")

# Make dialog box, with channel, threshold and "subdirectory" inputs
gd = GenericDialog("Insert values")
gd.addStringField("1. channel (DAPI/Tub)", 'c1')
gd.addNumericField("1. channel lower threshold: ", 0, 0)
gd.addStringField("2. channel", 'c2')
gd.addNumericField("2. channel lower threshold: ", 0, 0)
gd.addChoice("Quantify by:", ["Tubulin area", "DAPI #"], '')
gd.showDialog()

# Assign values from dialog
channel1, channel2 = gd.getNextString(), gd.getNextString()
lowth1, lowth2 = gd.getNextNumber(), gd.getNextNumber()

# Check if the chosen folder has subdirectories, or simply just a folder with pictures
for root, dirs, files in os.walk(directory, topdown=True):
    if dirs:
        data, sub = getfilesDIRS()
        break
    else:
        data, sub = getfilesNoDIRS()
        break

#If the chosen directory does not contain ORG files; output error
if len(data[0]) != 2:
    sys.exit("Channels should be written as ex 'c1'")
Exemple #21
0
if gd.getNextChoice() == "Yes, enable thresholding mode":
    thresholdMode = True

# Set default thresholds:
#	round_threshold is the minimum roundness a roi must have to be considered an organoid for the isOrganoid column
#	area_threshold is the minimum area a roi must have to be considered an organoid for the isorganoid column
#	minimum_size is the minimum area to be considered an ROI

gd = GenericDialog("Other Thresholds.")
gd.addMessage("Ajust after you have determined if new thresholds are needed.")
gd.addStringField("Round threshold", "0.62")
gd.addStringField("Area Threshold", "50000")
gd.addStringField("Minimum Size", "3000")
gd.showDialog()

round_threshold = float(gd.getNextString())
area_threshold = float(gd.getNextString())
minimum_size = float(gd.getNextString())

#set pix_width and pix_height to real dimensions per pixel

gd = GenericDialog("Dimension Options")
gd.addMessage(
    "Conversion from pixles to uM :Evos 10X pixle width/height = 0.8777017 uM")
gd.addMessage(
    "Conversion from pixles to uM :Evos 4X  pixle width/height = 2.1546047 uM")
gd.addMessage(
    "Conversion from pixles to uM :Calculate for your objective and enter below"
)
gd.addStringField("Pixel Width:", "0.8777017")
gd.addStringField("Pixel Height:", "0.8777017")
def run():
    types = ['oneDay', 'oneFolder', 'oneFile', 'mapmaneger', 'test']

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

    if gd.wasCanceled():
        print 'user cancel the plugin'
        return 0
    else:
        srcType = gd.getNextChoiceIndex()

        #run one day
        if srcType == 0:
            dayFolder = DirectoryChooser(
                'Please Choose A Directory Of .tif Files').getDirectory()
            if not os.path.isdir(dayFolder):
                bab.bPrintLog(
                    '\nERROR: runOneDay() did not find folder: ' + dayFolder +
                    '\n', 0)
                return 0

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

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

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

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

            if len(mapFolders) == 0:
                bab.bPrintLog('\nERROR: no map folder found', 0)
                return 0

            bab.bPrintLog('Map Folder number: ' + str(len(mapFolders)), 0)
            #put option here so we do not have to click for each folder
            sourceFolders = [
                mapPath + '/' + mapFolder + '/raw/' for mapFolder in mapFolders
            ]
            if bab.Options(sourceFolders[0]):
                for sourceFolder in sourceFolders:
                    bab.runOneFolder(sourceFolder)

        if srcType == 4:  #for test
            gd = GenericDialog('Choose maps')
            gd.addStringField('maps name initials', 'F58,F59')
            gd.showDialog()
            maps = gd.getNextString().split(',')
            maps = tuple(maps)
            bab.bPrintLog(maps[0], 0)
def run():
	types = ['oneDay','oneFolder','oneFile','mapmaneger','test']

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



	if gd.wasCanceled():
		print 'user cancel the plugin'
		return 0
	else:
		srcType = gd.getNextChoiceIndex()

		#run one day
		if srcType == 0:
			dayFolder = DirectoryChooser('Please Choose A Directory Of .tif Files').getDirectory()
			if not os.path.isdir(dayFolder):
				bab.bPrintLog('\nERROR: runOneDay() did not find folder: ' + dayFolder + '\n',0)
				return 0

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

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

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

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

		if srcType == 4: #for test
			gd = GenericDialog('Choose maps')
			gd.addStringField('maps name initials','F58,F59')
			gd.showDialog()
			maps = gd.getNextString().split(',')
			maps = tuple(maps)
			bab.bPrintLog(maps[0],0)
Exemple #24
0
mipChoices = ["yes: tiff", "yes: jpg"]
overwriteList = []
startTime = time.time()
imageCount = 0

gd = GenericDialog("Set binarization.py Options")
gd.addStringField("String to identify your input images", "_deconv")
gd.addRadioButtonGroup("Output", outDirChoices, 3, 1, outDirChoices[0])
gd.addRadioButtonGroup("Threshold Settings", thresholdChoices, 3, 1, thresholdChoices[0])
gd.addRadioButtonGroup("Overwrite", overwriteChoices, 2, 1, overwriteChoices[0])
gd.addCheckboxGroup(2, 1, mipChoices, [False, False], ["Do you want maximum intensity projections of your images?"])
gd.showDialog()
if gd.wasCanceled():
    exit()

fileID = gd.getNextString()
outDirPref = gd.getNextRadioButton()
thresholdPref = gd.getNextRadioButton()
overwritePref = gd.getNextRadioButton()
mipPrefTIFF = gd.getNextBoolean()
mipPrefJPG = gd.getNextBoolean()
IJ.redirectErrorMessages(True)

inDir = IJ.getDirectory("Choose Directory Containing Input Files")
if inDir is None:
    exit('No input directory selected!')

if outDirPref == outDirChoices[2]:
    outDir = inDir
else:
    outDir = IJ.getDirectory("Choose Directory For Output")
Exemple #25
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
    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()
    overlap  = dialog.getNextNumber()
    c        = dialog.getNextNumber()
    step     = interval - overlap


    
    ImageConverter( imgSource ).convertToGray32()
    
    stat    = FloatStatistics( imgSource.getProcessor() )
    normalizeBy = stat.max
    imgSource.getProcessor().multiply( 1.0 / normalizeBy )
Exemple #27
0
desktop.browse(uri)


session = None
channel = None

DIALOG = True

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

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

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

	gui = GenericDialogPlus("Parameters")
	gui.addFileField("Select a python script file to upload on the server (*.py)  : ", "")
	gui.showDialog()
	if gui.wasOKed():
	    LOCAL_PREDICTION_SCRIPT   = gui.getNextString()

Exemple #28
0
if choice == "10X Evos":
	pix_width = 0.8777017
	pix_height = 0.8777017
if choice == "4X Evos":
	pix_width = 2.1546047
	pix_height = 2.1546047

if choice == "Other":
	gd = GenericDialog("Dimension Options")

	gd.addMessage("Conversion from pixels to uM :Calculate for your objective and enter below")
	gd.addStringField("Pixel Width:", "0.8777017")
	gd.addStringField("Pixel Height:", "0.8777017")
	gd.showDialog()

	pix_width = gd.getNextString()
	pix_height = gd.getNextString()



# Get input and output directories with GUI 

dc = DirectoryChooser("Choose an input directory")  
inputDirectory = dc.getDirectory() 

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

with open(outputDirectory + "output_"+datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")+".csv", "w") as output:

# set the output column names for the csv sheet
Exemple #29
0
#commands = [c for c in ij.Menus.getCommands().keySet()]
# Above, equivalent list as below:
commands = Menus.getCommands().keySet().toArray()
gd = GenericDialog('Command Launcher')
gd.addStringField('Command: ', '');
prompt = gd.getStringFields().get(0)
prompt.setForeground(Color.red)

class TypeListener(TextListener):
	def textValueChanged(self, tvc):
		if prompt.getText() in commands:
			prompt.setForeground(Color.black)
			return
		prompt.setForeground(Color.red)
		# or loop:
		#for c in commands:
		#	if c == text:
		#		prompt.setForeground(Color.black)
		#		return
		#
		#prompt.setForeground(Color.red)

prompt.addTextListener(TypeListener())
gd.showDialog()
if not gd.wasCanceled(): IJ.doCommand(gd.getNextString())

# This python version does not encapsulate the values of the variables, so they are all global when defined outside the class definition.
# In contrast, the lisp 'let' definitions encapsulates them in full
# As an advantage, each python script executes within its own namespace, whereas clojure scripts run all within a unique static interpreter.
thresholds = {}

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

if gd.getNextChoice() == "Yes, enable thresholding mode":
    thresholdMode = True
    
if thresholdMode == False:
    gd = GenericDialog("Set Thresholds")
    gd.addStringField("Lower bound for Red", "90")
    gd.addStringField("Lower bound for Green", "100")
    gd.addStringField("Lower bound for Blue", "100")
    gd.showDialog()
    thresholds["Red"] = int(gd.getNextString());
    thresholds["Green"] = int(gd.getNextString());
    thresholds["Blue"] = int(gd.getNextString());
    
gd = GenericDialog("Other Thresholds.")
gd.addMessage("Adjust after you have determined if new thresholds are needed.")
    

# Set default thresholds:
#	minimum_size is the minimum area to be considered an ROI

	
minimum_size=[]
maximum_size=[]

for x,color in enumerate(colors2):
Exemple #31
0
gd.addStringField("File_extension", ".tif")
gd.addStringField("File_name_contains", "")
gd.addCheckbox("Keep directory structure when saving", True)
gd.addCheckbox("Show tracks", False)
gd.showDialog()

Pixel_calibration = gd.getNextNumber()
Time_interval = gd.getNextNumber()
LINKING_MAX_DISTANCE = gd.getNextNumber()
GAP_CLOSING_MAX_DISTANCE = gd.getNextNumber()
MAX_FRAME_GAP = int(gd.getNextNumber())
ALLOW_TRACK_SPLITTING = gd.getNextBoolean()
SPLITTING_MAX_DISTANCE = gd.getNextNumber()
ALLOW_TRACK_MERGING = gd.getNextBoolean()
MERGING_MAX_DISTANCE = gd.getNextNumber()
ext = gd.getNextString()
containString = gd.getNextString()
keepDirectories = gd.getNextBoolean()
showtracks = gd.getNextBoolean()

#print(LINKING_MAX_DISTANCE)
#print(ALLOW_TRACK_SPLITTING)
#print(SPLITTING_MAX_DISTANCE)
#print(ALLOW_TRACK_MERGING)
#print(MERGING_MAX_DISTANCE)
#print(LINKING_MAX_DISTANCE)
#print(ext)

print(Pixel_calibration)
print(Time_interval)
Exemple #32
0
    sq1 = (x1 - x2) * (x1 - x2)
    sq2 = (y1 - y2) * (y1 - y2)
    dis = math.sqrt(sq1 + sq2)
    return (dis)


while True:

    checkbox = False
    while checkbox == False:
        gd = GenericDialog("Title here")
        gd.addStringField("id", "")
        gd.addCheckbox("Same Image", True)
        gd.showDialog()
        checkbox = gd.getNextBoolean()
        id = gd.getNextString()
        if checkbox == False:
            IJ.run("Open Next")
        else:
            break

    imp = IJ.getImage()
    IJ.setTool("multipoint")
    WaitForUserDialog("make 11 points").show()

    proi = imp.getRoi()
    p = proi.getPolygon()
    xpts = p.xpoints
    ypts = p.ypoints

    xpts.insert(0,
Exemple #33
0
from fiji.util.gui import GenericDialogPlus
from ij import IJ

session = None
channel = None

DIALOG = True

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

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

    gui = GenericDialogPlus("Parameters")
    gui.addFileField("Select an input file (*.tif) : ", "")
    gui.showDialog()
    if gui.wasOKed():
        LOCAL_IMAGE_FILENAME = gui.getNextString()

    LOCAL_RESULT_FILENAME = LOCAL_IMAGE_FILENAME + "_prediction.tif"

jsch = JSch()

# SSH Connection to DeepLearning server
IJ.log("-- Connection to Deep Learning Server")
time0 = time.time()
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)
Exemple #35
0
name = imp.getTitle()[0:2]
if not name.isdigit():
    name = imp.getTitle()[0:1]
#name = int(''.join(filter(str.isdigit, name)))
IJ.run("Select All")
IJ.run("Duplicate...", "check and close")
newimp = IJ.getImage()
rm.runCommand(newimp, "Show All")
if rm.getCount() > 1:
    rm.setSelectedIndexes(range(rm.getCount()))
    rm.runCommand(newimp, "Combine")
else:
    rm.select(newimp, 0)
IJ.run("Make Inverse")
IJ.run("Cut")
gd = GenericDialog("suffix")
gd.addStringField("suffix:", "")
gd.showDialog()
suffix = gd.getNextString()
#ync = YesNoCancelDialog(None, "intensity (yes) or coverage (no or cancel)", "intensity (yes) or coverage (no or cancel)");
#if ync.yesPressed():
IJ.saveAs("Tiff", path + "\\prepared\\" + name + suffix + ".tif")
#rm.runCommand("Delete")
#else:
#IJ.saveAs("Tiff", path + "\\coverage\\" + name + suffix + ".tif");
#IJ.saveAs("Tiff", path + "\\MTs\\prepared\\" + name + suffix + ".tif");
#IJ.run("Undo");
#ij.RUN("mAKE iNVERSE");
#ij.RUN("cUT");
#ij.SAVEaS("tIFF", PATH + "PREPARED\\" + NAME + "P.TIF");
#rm.runCommand("Save", path + "\\MTs\\prepared\\" + name + suffix + ".zip")
Exemple #36
0
gd = GenericDialog("Set Threshold Mode")
gd.addChoice("Would you like to enable thresholding mode?", ["No, run the normal macro", "Yes, enable thresholding mode"], "No")
gd.showDialog()
if gd.getNextChoice() == "Yes, enable thresholding mode":
	thresholdMode = True

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


thresholds = {}
thresholds["Red"] = int(gd.getNextString()
)
thresholds["Green"] = int(gd.getNextString()
)
thresholds["Blue"] = int(gd.getNextString())


# Set default thresholds:
#	minimum_size is the minimum area to be considered an ROI

gd = GenericDialog("Other Thresholds.")
gd.addMessage("Ajust after you have determined if new thresholds are needed.")
gd.addStringField("Minimum Size of ROI", "60")
gd.addStringField("Maximum Size of ROI", "1000")

gd.showDialog()
        ER_mean = (selection_mean())
        ER.append(ER_mean)
        IJ.run(imp, "Draw", "slice")

    try:
        with open(Quant) as infile:
            reader = csv.reader(infile)
            row_count = sum(1 for row in reader)
            cell_number = row_count
    except:
        cell_number = 1

    gd = GenericDialog("Type cell number")
    gd.addStringField("Cell number", str(cell_number))
    gd.showDialog()
    number = gd.getNextString()

    ER1 = ER[0]
    ER2 = ER[1]
    ER3 = ER[2]
    total_ER = sum(ER)
    average_ER = total_ER / 3
    net_ER = average_ER - background
    try:
        net_golgi = average_max - background
        t_index = net_golgi / net_ER
    except:
        net_golgi = 'Pixels saturated in Transport Channel'
        t_index = 'Pixels saturated in Transport Channel'
        # mean max calculations
        mean_int = [ai - bi for ai, bi in zip(mean_int, bck_int)]
chooser = JFileChooser()
chooser.setDialogTitle("Choose plate grids")
chooser.setMultiSelectionEnabled(True)
chooser.setCurrentDirectory( File(os.path.expanduser("~")))
chooser.showOpenDialog(JPanel())

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

if len(fp) != 0:
    gd = GenericDialog("Name your output file")
    gd.addStringField("Score file name", "scores.csv")
    gd.showDialog()
    if not gd.wasCanceled():
        scoreFile = gd.getNextString()
        scoreFile = os.path.join( os.path.split(fp[0])[0], scoreFile)
        cropDir = os.path.splitext( scoreFile)[0] + "_cropped"
        # Initialize the grid readers
        plateGrid = GridSet(fp,scoreFile,cropDir)
        plateGrid.openNext()
        # Show the GUI
        frame.setVisible(True)
    else:
        pass
else:
    pass



    def dialog(self):
        """
        Open the classifier dialog window and return the paramters
        chosen.
        """

        # determine how many images are currently open
        image_count = WindowManager.getImageCount()
        image_titles = list(WindowManager.getImageTitles())
        image_titles.append("None")

        # now open a dialog to let the user set options
        path_listener = SetPathListener(self.path)
        path_button = TrimmedButton("Output directory",0)
        path_button.addActionListener(path_listener)

        dlg = GenericDialog("Create classifier data (v"+__version__+")")
        dlg.addMessage("Session ID: "+ str(self.session_id))
        dlg.addMessage("")
        dlg.addMessage("Select the ROI you want to save")
        dlg.addNumericField("Window size (pixels): ", self.window_size, 0)
        dlg.addChoice("Class label: ", DEFAULT_CLASSES+['Other...'], DEFAULT_CLASSES[0])
        dlg.addStringField("Class label (if other): ", "")
        dlg.addChoice("Image file #1 (BF):",image_titles,"None")
        dlg.addChoice("Image file #2 (GFP):",image_titles,"None")
        dlg.addChoice("Image file #3 (RFP):",image_titles,"None")
        dlg.addChoice("Mask file:",image_titles,"None")
        dlg.addCheckbox("Rename ROIs", True)
        dlg.addCheckbox("Exclude edges", True)
        dlg.addCheckbox("Save ROI zip", True)
        dlg.addCheckbox("Save classifier details", True)
        dlg.add(path_button)
        dlg.showDialog()

        # handle the cancelled dialog box
        if dlg.wasCanceled():
            return None


        label_option = dlg.getNextChoice()
        if label_option == 'Other...':
            label = dlg.getNextString()
        else:
            label = label_option



        # get the root path from the path listener
        root_path = path_listener.path

        if not os.path.isdir(root_path):
            w_dlg = GenericDialog("Warning")
            w_dlg.addMessage("Root path does not exist!!")
            w_dlg.showDialog()
            return None

        # try to make the directory for the label if it does not exist
        label_path = os.path.join(root_path, label)
        check_and_makedir(label_path)

		# get the options
        dialog_options = {'window_size': dlg.getNextNumber(),
                            'label': label,
                            'BF': dlg.getNextChoice(),
                            'GFP': dlg.getNextChoice(),
                            'RFP': dlg.getNextChoice(),
                            'mask': dlg.getNextChoice(),
                            'rename': dlg.getNextBoolean(),
                            'edges': dlg.getNextBoolean(),
                            'zip': dlg.getNextBoolean(),
                            'save': dlg.getNextBoolean(),
                            'path': label_path}

        # check that we actually selected an image file
        if all([dialog_options[d] == "None" for d in ['BF','GFP','RFP']]):
            w_dlg = GenericDialog("Warning")
            w_dlg.addMessage("You must select an image stream.")
            w_dlg.showDialog()
            return None

        # grab the contents and return these as a dictionary
        return dialog_options