Exemple #1
0
def get_user_params(event):
    """ Allows user to select file and user parameters

    Parameters
    ----------
    event : Event
        Waits for get_user_params_JB JButton to be pressed
    
    Returns
    -------
    dict
        Dict containing filename, number of Gaussians to fit,
        % of dataset to import, whether to specify grey value
        limits, minimum grey value and maximum grey value to 
        consider (optional)
    """
    # Open user dialog
    gui = GenericDialogPlus("Define user parameters")
    gui.addFileField("Image filename", "Select image file")
    gui.addNumericField("Number of Gaussians to fit: ", 2, 0)
    gui.addNumericField("Percentage of dataset to import: ", 15, 0)
    gui.addCheckbox("Specify grey value limits?", False)
    gui.addNumericField("Min grey value (optional): ", 0, 0)
    gui.addNumericField("Max grey value (optional): ", 255, 0)
    gui.showDialog()

    # Extract user parameters
    if gui.wasOKed():
        user_params = {}  # empty dict
        user_params['img_fname'] = str(gui.getNextString())
        user_params['n_gaussians'] = int(gui.getNextNumber())
        user_params['pct_stack_import'] = float(gui.getNextNumber())
        user_params['specify_gv'] = gui.getNextBoolean()
        user_params['min_gv'] = float(gui.getNextNumber())
        user_params['max_gv'] = float(gui.getNextNumber())

    # Create results directory
    results_dir = os.path.splitext(user_params['img_fname'])[0] + "_results"
    if os.path.isdir(results_dir) == False:
        os.mkdir(results_dir)
    print("Results directory: {}".format(results_dir))

    # Write user parameters to text file
    user_params_fname = os.path.join(results_dir, "Users_Params.csv")
    with open(user_params_fname, "wb") as f:
        w = csv.DictWriter(f, user_params.keys())
        w.writeheader()
        w.writerow(user_params)

    # Write directory to look for user params to text file in main/
    temp_user_dir = os.path.join(os.path.dirname(__file__),
                                 "temp_user_dir.txt")
    if os.path.isfile(temp_user_dir) == True:
        os.remove(temp_user_dir)  # delete temp_user_dir.txt if present
    f = open(temp_user_dir, "w")
    f.write(user_params_fname)
    f.close()

    return user_params
Exemple #2
0
def get_parameters(p):
  gd = GenericDialogPlus("Please enter parameters")

  for k in p['expose_to_gui']['value']:
    if p[k]['type'] == 'boolean':
      gd.addCheckbox(k, p[k]['value'])
    elif p[k]['type'] == 'folder':
      gd.addDirectoryField(k, p[k]['value'], 100)	
    elif p[k]['type'] == 'file':
      gd.addFileField(k, p[k]['value'], 100)	
    elif p[k]['type'] == 'string':
      if p[k]['choices']:
        gd.addChoice(k, p[k]['choices'], p[k]['value'])	
      else:
        gd.addStringField(k, p[k]['value'])	 
    elif p[k]['type'] == 'int':
      if p[k]['choices']:
        gd.addChoice(k, p[k]['choices'], p[k]['value'])	
      else:
        gd.addNumericField(k, p[k]['value'], 0)	 
    elif p[k]['type'] == 'float':
      gd.addNumericField(k, p[k]['value'], 2)
  
  gd.showDialog()
  if gd.wasCanceled():
    return

  for k in p['expose_to_gui']['value']:
    if p[k]['type'] == 'boolean':
      p[k]['value'] = gd.getNextBoolean()
    elif p[k]['type'] == 'folder' or p[k]['type'] == 'file':
      p[k]['value'] = gd.getNextString()
    elif p[k]['type'] == 'string':
      if p[k]['choices']:
        p[k]['value'] = gd.getNextChoice()	
      else:
        p[k]['value'] = gd.getNextString()	 
    elif p[k]['type'] == 'int':
      if p[k]['choices']:
        p[k]['value'] = int(gd.getNextChoice())	
      else:
        p[k]['value'] = int(gd.getNextNumber()) 
    elif p[k]['type'] == 'float':
        p[k]['value'] = gd.getNextNumber()
    
  return p
def make_dialog():

	parameters = {}

	gd = GenericDialogPlus("Grid Stitch SDC Data")
	gd.addMessage(  "Warning!\n"\
					"In order to display a fused image upon completion of stitching\n"\
					"please disable Fiji's ImageJ2 options. When enabled an ImageJ\n"\
					"exception will be displayed upon completion. This exception can\n"
					"be safely ignored.")
	gd.addMessage(  "Information\n"\
					"This plugin is a wrapper around the Fiji 'Grid Stitching' plugin.\n"\
					"It allows tiles generated in SlideBook to be directly stitched by\n"\
					"by first writing out the individual tiles, executing the 'Grid Stitching'\n"\
					"plugin and writing the fused image to disk.")
	gd.addMessage("")										
	gd.addNumericField("grid_size_x", 3, 0)
	gd.addNumericField("grid_size_y", 3, 0)
	gd.addCheckbox("Select channel",False)
	gd.addNumericField("", 0, 0)		
	gd.addCheckbox("Are the Z slices separate files?",False)
	gd.addDirectoryField("directory", "", 50)
	
	gd.showDialog()
	if (gd.wasCanceled()): return
		
	parameters['gridX'] = int(math.ceil(gd.getNextNumber()))
	parameters['gridY'] = int(math.ceil(gd.getNextNumber()))
	parameters['select_channel'] = gd.getNextBoolean()
	parameters['channel'] = None
	if parameters['select_channel']:
		parameters['channel'] = int(gd.getNextNumber())
	parameters['separate_z'] = gd.getNextBoolean()
	directory = str(gd.getNextString())	
	if directory is None:
	# User canceled the dialog
		return None
	else:
		directory = os.path.abspath(directory)
		parameters['directory'] = directory + os.path.sep

	return parameters
Exemple #4
0
def optionsDialog():
	dialog = GenericDialogPlus("Automated Size Analysis")
	dialog.addDirectoryField("Image Directory", "")
	dialog.addStringField("Output Subdirectory", "output", 20)
	dialog.addStringField("Minimum Pixel Size", "50000", 20)
	dialog.addStringField("Minimum Roundness", "0.4", 20)
	dialog.addStringField("Gaussian Blur", "6", 20)
	dialog.addStringField("Rotation Steps", "3", 20)
        dialog.addStringField("Thresholds", ",".join(THRESHOLDS), 20)
	dialog.addCheckbox("Rotate Images", True)
	dialog.addCheckbox("Multiple Thresholds", True)
	dialog.showDialog()

	# Check if canceled
	if dialog.wasCanceled(): return None

	textVals = [x.text for x in dialog.getStringFields()]
	boolVals = [x.getState() for x in dialog.getCheckboxes()]

	return textVals + boolVals
Exemple #5
0
def run():
    gd = GenericDialogPlus("ND2 Conversion Tool")
    gd.addMessage("This plugin uses BioFormats to convert ND2 images to JPEG for further processing in ImageJ.")
    gd.addDirectoryOrFileField("Input: ", "G:\\Subdir testing\\") #srcDir
    gd.addDirectoryOrFileField("Output: ", "G:\\Subdir testing\\") #dstDir
    gd.addStringField("File name contains: ", "") #nameContains
    gd.addCheckbox("Preserve directory structure?", True) #keepDirs
    gd.addCheckbox("Run in headless mode?", True) #anneBoleyn 
    gd.addCheckbox("Overwrite existing output files?", True)
    gd.showDialog()
    if gd.wasCanceled():
        return
    srcDir = gd.getNextString()
    dstDir = gd.getNextString()
    nameContains = gd.getNextString()
    keepDirectories = gd.getNextBoolean()
    anneBoleyn = gd.getNextBoolean()
    overOut = gd.getNextBoolean()
    IJ.run("Input/Output...", "jpeg=100")
    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            # Check for file extension
            if not filename.endswith(".nd2"):
                continue
            # Check for file name pattern
            if nameContains not in filename:
                continue
            process(srcDir, dstDir, nameContains, root, filename, keepDirectories, anneBoleyn, overOut)
scaleX = calib.pixelWidth / calib.pixelDepth * zoom;
scaleY = calib.pixelHeight / calib.pixelDepth * zoom;
scaleZ = 1.0 * zoom;

# initialize state
input = None;
formerT = None;
resultCylinderMaxProjection = None;
resultMaxProjection = None;
spots = None;
circles = None;
blobs = None;

# build up user interface
gdp = GenericDialogPlus("Spot detection workflow");
gdp.addMessage("Noise and background subtraction (DoG)");
gdp.addCheckbox("Do noise and background subtraction ", formerDoNoiseAndBackgroundRemoval);
gdp.addSlider("Sigma 1 (in 0.1 pixel)", 0, 100, formerSigma1);
gdp.addSlider("Sigma 2 (in 0.1 pixel)", 0, 100, formerSigma2);
gdp.addMessage("Rigid transform");
gdp.addCheckbox("Do rigid transformation", formerDoRigidTransform);
gdp.addSlider("Translation X (in pixel)", -100, 100, formerTranslationX);
gdp.addSlider("Translation Y (in pixel)", -100, 100, formerTranslationY);
gdp.addSlider("Translation Z (in pixel)", -100, 100, formerTranslationZ);
gdp.addSlider("Rotation X (in degrees)", -180, 180, formerRotationX);
gdp.addSlider("Rotation Y (in degrees)", -180, 180, formerRotationY);
gdp.addSlider("Rotation Z (in degrees)", -180, 180, formerRotationZ);
gdp.addMessage("Spot detection")
gdp.addCheckbox("Do spot detection", formerDoSpotDetection);
gdp.addSlider("Tolerance", 0, 100, formerTolerance);
gdp.addSlider("Threshold", 0, 100, formerThreshold);
Exemple #7
0
## Home-Made module
from Template_Matching.MatchTemplate_Module import getHit_Template, CornerToCenter
from Template_Matching.NonMaximaSupression_Py2 import NMS

## Create GUI
Win = GenericDialogPlus("Multiple Template Matching")
Win.addDirectoryOrFileField("Template file or templates folder",
                            prefs.get("TemplatePath", "template(s)"))
Win.addDirectoryOrFileField("Image file or images folder",
                            prefs.get("ImagePath", "image(s)"))
Win.addFileField("Rectangular_search_ROI (optional)",
                 prefs.get("RoiPath", "searchRoi"))

# Template pre-processing
Win.addCheckbox("Flip_template_vertically", prefs.getInt("FlipV", False))
Win.addCheckbox("Flip_template_horizontally", prefs.getInt("FlipH", False))
Win.addStringField("Rotate template by ..(comma-separated)",
                   prefs.get("Angles", ""))

# Template matchign parameters
Win.addChoice("Matching_method", [
    "Normalised Square Difference", "Normalised cross-correlation",
    "Normalised 0-mean cross-correlation"
], prefs.get("Method", "Normalised 0-mean cross-correlation"))
Win.addNumericField("Number_of_templates expected", prefs.getInt("N_hit", 1),
                    0)
Win.addMessage("If more than 1 template expected :")
Win.addNumericField("Score_Threshold [0-1]",
                    prefs.getFloat("Score_Threshold", 0.5), 2)
#Win.addNumericField("Min_peak_height relative to neighborhood ([0-1], decrease to get more hits)", prefs.getFloat("Tolerance",0.1), 2)
Exemple #8
0
def previewDialog(imp):
	gd = GenericDialogPlus("FRETENATOR")

	#create a list of the channels in the provided imagePlus
	types = []
	for i in xrange(1, imp.getNChannels()+1):
		types.append(str(i))
	gd.addMessage("""Rowe, J. H, Rizza, A., Jones A. M. (2022) Quantifying phytohormones
	in vivo with FRET biosensors and the FRETENATOR analysis toolset
	Methods in Molecular Biology
	Rowe, JH., Grangé-Guermente, M., Exposito-Rodriguez, M.,Wimalasekera, R., Lenz, M.,
	Shetty, K., Cutler, S., Jones, AM., Next-generation ABACUS biosensors reveal cellular
	ABA dynamics driving root growth at low aerial humidity
	""")
	#user can pick which channel to base the segmentation on
	if len(types)>2:
		gd.addChoice("Channel number to use for segmentation", types, types[2])
		gd.addChoice("Channel number to use for donor", types, types[0])
		gd.addChoice("Channel number to use for acceptor (FRET)", types, types[1])
		gd.addChoice("Channel number to use for acceptor", types, types[2])
		#print('YAY')
	else:
		gd.addChoice("Channel number to use for segmentation", types, types[-1])
		gd.addChoice("Channel number to use for donor", types, types[0])
		gd.addChoice("Channel number to use for acceptor (FRET)", types, types[-2])
		gd.addChoice("Channel number to use for acceptor", types, types[-1])
	
	methods=["Otsu","Default", "Huang", "Intermodes", "IsoData", "IJ_IsoData", "Li", "MaxEntropy", "Mean", "MinError", "Minimum", "Moments", "Percentile", "RenyiEntropy", "Shanbhag", "Triangle", "Yen"]
	gd.addChoice("Autosegmentation method", methods, methods[0])
	intensities=["254", "4094", "65534"]
	gd.addChoice("Max Intensity", intensities, intensities[-1])
	gd.addSlider("Small DoG sigma", 0.5, 10, 0.8, 0.1)
	gd.addSlider("Large DoG sigma", 0.5, 20, 4 ,0.1)
	gd.addCheckbox("TopHat background subtraction? (Slower, but better) ", False)
	gd.addSlider("TopHat sigma", 5, 20, 8 ,0.1)
	gd.setModal(False)
	gd.addCheckbox("Manually set threshold? ", False)
	gd.addSlider("Manual threshold", 10, 65534, 2000, 1)
	dilationOptions=["0", "1", "2","3", "4", "5", "6"]
	gd.addChoice("Dilation?", dilationOptions, "0")
	gd.addCheckbox("Size exclusion of ROI? ", False)
	gd.addSlider("Minimum ROI size", 0, 9999, 20, 1)
	gd.addSlider("Maximum ROI size", 1, 10000, 10000, 1)
	gd.addCheckbox("Create nearest point projection with outlines (SLOW)? ", True)
	gd.addCheckbox("Watershed object splitting? ", True)
	gd.showDialog()

		
	cal = imp.getCalibration()
	pixelAspect=(cal.pixelDepth/cal.pixelWidth)
	
	originalTitle=imp1.getTitle()
	
	choices=gd.getChoices()
	sliders=gd.getSliders()
	checkboxes=gd.getCheckboxes()		
	segmentChannel=int(choices.get(0).getSelectedItem())
	donorChannel=int(choices.get(1).getSelectedItem())
	acceptorChannel=int(choices.get(2).getSelectedItem())
	acceptorChannel2=int(choices.get(3).getSelectedItem())
	thresholdMethod=choices.get(4).getSelectedItem()
	maxIntensity=int(choices.get(5).getSelectedItem())
	gaussianSigma=sliders.get(0).getValue()/10.0
	largeDoGSigma = gd.sliders.get(1).getValue()/10.0
	topHat=gd.checkboxes.get(0).getState()
	topHatSigma=gd.sliders.get(2).getValue()/10.0
	
	manualSegment = gd.checkboxes.get(1).getState()
	manualThreshold=gd.sliders.get(3).getValue()
	dilation=int(choices.get(6).getSelectedItem())
	sizeExclude=gd.checkboxes.get(2).getState()
	minSize = gd.sliders.get(4).getValue()
	maxSize = gd.sliders.get(5).getValue()
	watershed = gd.checkboxes.get(4).getState()
	#print dir(gd.sliders.get(5))
	#print maxSize
	
	segmentChannelOld=segmentChannel
	thresholdMethodOld=thresholdMethod
	maxIntensityOld=maxIntensity
	gaussianSigmaOld=gaussianSigma
	largeDoGSigmaOld= largeDoGSigma
	topHatOld=topHat
	topHatSigmaOld=topHatSigma
	manualSegmentOld= manualSegment
	manualThresholdOld=manualThreshold
	dilationOld=dilation
	sizeExcludeOld=sizeExclude
	minSizeOld=minSize
	maxSizeOld=maxSize
	watershedOld=watershed
	clij2.clear()
	
	segmentImp=extractChannel(imp1, segmentChannel, 0)

	try:
		gfx1=clij2.push(segmentImp)
		gfx2=clij2.create(gfx1)
		gfx3=clij2.create(gfx1)
		gfx4=clij2.create(gfx1)
		gfx5=clij2.create(gfx1)
		gfx7=clij2.create([imp.getWidth(), imp.getHeight()])
	except:	
		try:
		
			Thread.sleep(500)
			print("Succeeded to sending to graphics card on the second time...")
			gfx1=clij2.push(segmentImp)
			gfx2=clij2.create(gfx1)
			gfx3=clij2.create(gfx1)
			gfx4=clij2.create(gfx1)
			gfx5=clij2.create(gfx1)
			gfx7=clij2.create([imp.getWidth(), imp.getHeight()])
		except:
			errorDialog("""Could not send image to graphics card, it may be too large!
		
			Easy solutions: Try	processing as 8-bit, cropping or scaling the image, or
			select a different CLIJ2 GPU.

			This issue is often intermittent, so trying again may also work! 

			See the "Big Images on x graphics cards' notes at:
			https://clij2.github.io/clij2-docs/troubleshooting for more solutions
			
			"""	+ str(clij2.reportMemory()) )


	gfx1,gfx2,gfx3,gfx4,gfx5 = segment(gfx1,gfx2,gfx3,gfx4,gfx5, gaussianSigma, thresholdMethod,maxIntensity, largeDoGSigma, pixelAspect, originalTitle, topHat, topHatSigma , manualSegment, manualThreshold, dilation,sizeExclude, minSize, maxSize, watershed)
	clij2.maximumZProjection(gfx5, gfx7)

	labelPrevImp= clij2.pull(gfx7)
	IJ.setMinAndMax(labelPrevImp, 0,clij2.getMaximumOfAllPixels(gfx7))
	labelPrevImp.setTitle("Preview segmentation")
	labelPrevImp.show()
	
	IJ.run("glasbey_inverted")
	
	while ((not gd.wasCanceled()) and not (gd.wasOKed())):
		

		segmentChannel=int(choices.get(0).getSelectedItem())
		donorChannel=int(choices.get(1).getSelectedItem())
		acceptorChannel=int(choices.get(2).getSelectedItem())
		acceptorChannel2=int(choices.get(3).getSelectedItem())
		thresholdMethod=choices.get(4).getSelectedItem()
		maxIntensity=int(choices.get(5).getSelectedItem())
		gaussianSigma=sliders.get(0).getValue()/10.0
		largeDoGSigma = gd.sliders.get(1).getValue()/10.0
		topHat=gd.checkboxes.get(0).getState()
		topHatSigma=gd.sliders.get(2).getValue()/10.0

		manualSegment = gd.checkboxes.get(1).getState()
		manualThreshold = gd.sliders.get(3).getValue()
		
		dilation=int(choices.get(6).getSelectedItem())
		
		sizeExclude=gd.checkboxes.get(2).getState()
		minSize = gd.sliders.get(4).getValue()
		maxSize = gd.sliders.get(5).getValue()
		watershed = gd.checkboxes.get(4).getState()
			
	
		if (segmentChannelOld !=segmentChannel or
		thresholdMethodOld !=thresholdMethod or
		maxIntensityOld !=maxIntensity or
		gaussianSigmaOld !=gaussianSigma or
		largeDoGSigmaOld != largeDoGSigma or
		topHatOld !=topHat or
		topHatSigmaOld !=topHatSigma or
		manualSegmentOld != manualSegment or
		manualThresholdOld !=manualThreshold or
		dilation != dilationOld or
		sizeExcludeOld!=sizeExclude or
		minSizeOld!=minSize or
		maxSizeOld!=maxSize or
		watershedOld!=watershed
		):
			if minSizeOld!=minSize:
				if minSize>=maxSize:
					maxSize=minSize+1
					gd.sliders.get(5).setValue(maxSize)
			if maxSizeOld!=maxSize:
				if minSize>=maxSize:
					minSize=maxSize-1
					gd.sliders.get(4).setValue(minSize)
			if segmentChannelOld!=segmentChannel:
					clij2.clear()
					segmentImp=extractChannel(imp1, segmentChannel, 0)
					gfx1=clij2.push(segmentImp)
					gfx2=clij2.create(gfx1)
					gfx3=clij2.create(gfx1)
					gfx4=clij2.create(gfx1)
					gfx5=clij2.create(gfx1)
					gfx7=clij2.create([imp.getWidth(), imp.getHeight()])
			gfx1,gfx2,gfx3,gfx4,gfx5 = segment(gfx1,gfx2,gfx3,gfx4,gfx5, gaussianSigma, thresholdMethod,maxIntensity, largeDoGSigma, pixelAspect, originalTitle, topHat,topHatSigma, manualSegment, manualThreshold, dilation,sizeExclude, minSize, maxSize, watershed)
			clij2.maximumZProjection(gfx5, gfx7)
			labelPrevImp.close()
			labelPrevImp= clij2.pull(gfx7)
			IJ.setMinAndMax(labelPrevImp, 0,clij2.getMaximumOfAllPixels(gfx7))
			labelPrevImp.setTitle("Preview segmentation")
			labelPrevImp.show()
			
			IJ.run("glasbey_inverted")
		
		segmentChannelOld=segmentChannel
		thresholdMethodOld=thresholdMethod
		maxIntensityOld=maxIntensity
		gaussianSigmaOld=gaussianSigma
		largeDoGSigmaOld = largeDoGSigma
		topHatOld=topHat
		topHatSigmaOld=topHatSigma
		manualSegmentOld= manualSegment
		manualThresholdOld=manualThreshold
		dilationOld=dilation
		sizeExcludeOld=sizeExclude
		minSizeOld=minSize
		maxSizeOld=maxSize
		watershedOld=watershed
		Thread.sleep(200)
	labelPrevImp.close()
	makeNearProj = gd.checkboxes.get(3).getState()
	return segmentChannel, donorChannel, acceptorChannel, acceptorChannel2, thresholdMethod, maxIntensity, gaussianSigma, largeDoGSigma, topHat, topHatSigma, manualSegment, manualThreshold, makeNearProj, dilation, sizeExclude, minSize, maxSize, watershed
Exemple #9
0
dest = IJ.getDirectory("image")
bck_path = 'optional'
gdp = GenericDialogPlus("FRET Assay, Version 3.4")
gdp.addDirectoryField("Output Location:", dest, 40)
gdp.addStringField("Processed Folder:", 'Processed_FRET', 40)
gdp.addStringField("FRET Outfile:", 'FRET_Outfile.csv', 40)
gdp.addStringField("Selection Radius:", '3', 10)
gdp.addStringField("Image interval (sec):", '4', 10)
gdp.addStringField("ZeroDivisionErorVal:", 'NA', 10)
gdp.addRadioButtonGroup("", fret_fura, 1, 2, "C1/C2 (FURA)")
#gdp.addCheckbox("Set Background to value:", False)
gdp.addFileField("background file:", bck_path, 40)
gdp.addToSameRow()
gdp.addStringField("", '0', 5)

gdp.addCheckbox("Apply Gaussian blur? Input sigma value:", False)
gdp.addToSameRow()
gdp.addStringField("", '4', 5)
gdp.addMessage(" ")
gdp.addMessage("Set R0 range (timepoint position x1 to x2):", boldFont)
gdp.addStringField("x1:", '2', 3)
gdp.addToSameRow()
gdp.addStringField(" x2:", '8', 3)
gdp.addMessage("Set output file headers:", boldFont)
gdp.addStringField("Channel 1:", 'A', 8)
gdp.addToSameRow()
gdp.addStringField("Channel 2:", 'B', 8)
gdp.addStringField("Channel Z/Channel W:", 'C', 8)
gdp.addToSameRow()
gdp.addStringField("R/R0:", 'D', 8)
gdp.showDialog()
Exemple #10
0
"",          "",          "",      "DAPI",      "GFP",    False,    True,            False,      "Otsu",    "Triangle", True,         8,     7,      50,        500
__dict__ = globals()
try:
	with open("savedSettings.json") as f:
	  thing = json.load(f)
	  for k, v in thing.iteritems():
	    __dict__[k] = v
	print(thing)
except Exception as e: print(e)
gd = GenericDialog("Analysis parameters")
gd.addDirectoryField("Image folder location", folderPath )
gd.addStringField("Image filename pattern", formatString, 70)
gd.addStringField("Group By", groupBy, 70)
gd.addStringField("Nuclear Stain Channel Name", nucChannel, 70)
gd.addStringField("Cardiomyocyte Image Channel Name", cmChannel, 70)
gd.addCheckbox("Are images stitched by well", stitched)
gd.addChoice("Nuclear thresholding method", methodsList, nucMethod)
gd.addCheckbox("Threshold nuclei by stack?", analyzeNucStack)
gd.addCheckbox("Are the cardiomyocyte images brightfield?", brightfield)
gd.addChoice("Cardiomyocyte thresholding method", methodsList,  cmMethod)
gd.addCheckbox("Threshold cardiomyocyes by stack?", analyzeCmStack)
gd.addNumericField("Rows per well", rowNo, 0)
gd.addNumericField("Columns per well", colNo, 0)
gd.addNumericField("Nuclear minimum size (pixels)", nucMinSize, 0)
gd.addNumericField("Cardiomyocyte minimum size (pixels)", cmMinSize, 0)
gd.showDialog()
folderPath = gd.getNextString() + "/"
formatString = gd.getNextString()
groupBy = re.findall(r"\w+", gd.getNextString())
nucChannel = gd.getNextString()
cmChannel = gd.getNextString()
Exemple #11
0
from fiji.util.gui import GenericDialogPlus
from ij.gui import GenericDialog
import os, shutil
import uuid
import sys

gdp=GenericDialogPlus("File Randomizer")
file_type = gdp.getNextString()
gdp.addStringField("File Extension ", '.tif',5)
x=gdp.addDirectoryField("Source:", " ")
gdp.addDirectoryField("Destination:", "(optional)")
gdp.addCheckbox("Copy & Move",False)
gdp.showDialog()
if gdp.wasOKed():
	file_type = gdp.getNextString().strip()
	source_path = gdp.getNextString().strip()
	dest_path = gdp.getNextString().strip()
	copymove=gdp.getNextBoolean()
	if dest_path == '(optional)':
		dest_path = source_path

else:
	exit()

##makes a new directory in the destination directory, called randomized.
key='key.csv'
r_key= os.path.join(dest_path,key)

if copymove ==True:
	randomized = 'randomized'
	path = os.path.join(dest_path,randomized)
gdp.addChoice("Transport Channel:", channels_available, tran_def)
gdp.addToSameRow()
gdp.addStringField("File Type: ", file_def, 5)
gdp.addChoice("  Golgi Channel:", channels_available, golgi_def)
gdp.addToSameRow()
gdp.addStringField("Processed File Extension: ", ext_def, 5)
gdp.addMessage("    ", italicFont)
gdp.addToSameRow()
gdp.addMessage("    ", italicFont)
gdp.addChoice(" Zoom: ", zoom, zoom_def)
gdp.addToSameRow()
gdp.addStringField("ER Selection Radius: ", radius_def, 5)
gdp.addChoice("View Mode:", color_options, color_def)
gdp.addMessage("------------------------------------------------------------", italicFont)
gdp.addMessage("  Advanced Options: ", italicFont)
gdp.addCheckbox("Always Select Golgi", golgi_select_def)
gdp.addToSameRow()
gdp.addCheckbox("Always Auto-Detect Golgi", auto_golgi_def)
gdp.addCheckbox("Mean_Max Detection", mean_max_def)
gdp.addToSameRow()
gdp.addCheckbox("Manual Background Selection", man_bck_def)
gdp.addCheckbox("Auto Position Image Window (position x,y):", auto_pos_def)

gdp.addStringField("x: ", xpos_def, 5)

gdp.addStringField("y: ", ypos_def, 5)
gdp.addMessage("------------------------------------------------------------", italicFont)
progress = images_processed(dest)
gdp.addMessage(str(progress[0])+'% Images Assayed' + ' ' +
               '(' + str(progress[2]) + '/' + str(progress[1]) + ')', italicFont)
gdp.addHelp("https://github.com/JohnSargeant-rgb")
Exemple #13
0
import csv
from ij.gui import Roi, PolygonRoi, GenericDialog, TextRoi, NonBlockingGenericDialog
import os
from fiji.util.gui import GenericDialogPlus
import re

gdp=GenericDialogPlus("File Derandomizer")
gdp.addFileField("'Key' path :", " ")
gdp.addFileField("Data file :", " ")
gdp.addDirectoryField("Derandomized path", "(optional)")
gdp.addDirectoryField("Processed Image Folder", " ")
gdp.addCheckbox("Derandomize Data File", True)
gdp.addCheckbox("Derandomize Image Folder", False)

gdp.showDialog()
if gdp.wasOKed():
	key_path = gdp.getNextString().strip()
	data_path = gdp.getNextString().strip()
	deR_path = gdp.getNextString().strip()
	pi_path= gdp.getNextString().strip()
	ddf=gdp.getNextBoolean()
	dif=gdp.getNextBoolean()
	if deR_path == "(optional)":
		deR_path = os.path.dirname(data_path) 
else:
	exit()


# function to return key for any value
def get_key(val):
    for key, value in random.items():
def previewDialog(imp):
    gd = GenericDialogPlus("Nuclear segmentation and quantification v1.01")

    #create a list of the channels in the provided imagePlus
    types = []
    for i in xrange(1, imp.getNChannels() + 1):
        types.append(str(i))

    #user can pick which channel to base the segmentation on
    gd.addChoice("Channel number to use for segmentation", types, types[0])
    gd.addChoice("Channel to quantify", types, types[0])
    methods = [
        "Otsu", "Default", "Huang", "Intermodes", "IsoData", "IJ_IsoData",
        "Li", "MaxEntropy", "Mean", "MinError", "Minimum", "Moments",
        "Percentile", "RenyiEntropy", "Shanbhag", "Triangle", "Yen"
    ]
    gd.addChoice("Autosegmentation method", methods, methods[0])
    intensities = ["254", "4094", "65534"]
    gd.addChoice("Max Intensity", intensities, intensities[-1])
    gd.addSlider("Small DoG sigma", 0.5, 10, 1, 0.1)
    gd.addSlider("Large DoG sigma", 0.5, 20, 5, 0.1)
    gd.addCheckbox("TopHat background subtraction? (Slower, but better) ",
                   True)
    gd.addSlider("TopHat sigma", 5, 20, 8, 0.1)
    gd.setModal(False)
    gd.addCheckbox("Manually set threshold? ", False)
    gd.addSlider("Manual threshold", 10, 65534, 2000, 1)

    gd.hideCancelButton()
    gd.showDialog()

    cal = imp.getCalibration()
    pixelAspect = (cal.pixelDepth / cal.pixelWidth)

    originalTitle = imp1.getTitle()

    choices = gd.getChoices()
    print choices
    sliders = gd.getSliders()
    checkboxes = gd.getCheckboxes()
    segmentChannel = int(choices.get(0).getSelectedItem())
    quantChannel = int(choices.get(1).getSelectedItem())
    thresholdMethod = choices.get(2).getSelectedItem()
    maxIntensity = int(choices.get(3).getSelectedItem())
    gaussianSigma = sliders.get(0).getValue() / 10.0
    largeDoGSigma = gd.sliders.get(1).getValue() / 10.0
    topHat = gd.checkboxes.get(0).getState()
    topHatSigma = gd.sliders.get(2).getValue() / 10.0

    manualSegment = gd.checkboxes.get(1).getState()
    manualThreshold = gd.sliders.get(3).getValue()

    segmentChannelOld = segmentChannel
    thresholdMethodOld = thresholdMethod
    maxIntensityOld = maxIntensity
    gaussianSigmaOld = gaussianSigma
    largeDoGSigmaOld = largeDoGSigma
    topHatOld = topHat
    topHatSigmaOld = topHatSigma
    manualSegmentOld = manualSegment
    manualThresholdOld = manualThreshold

    clij2.clear()

    segmentImp = extractChannel(imp1, segmentChannel, 0)

    try:
        gfx1 = clij2.push(segmentImp)
        gfx2 = clij2.create(gfx1)
        gfx3 = clij2.create(gfx1)
        gfx4 = clij2.create(gfx1)
        gfx5 = clij2.create(gfx1)
        gfx7 = clij2.create([imp.getWidth(), imp.getHeight()])
    except:
        try:

            Thread.sleep(500)
            IJ.log(
                "Succeeded to sending to graphics card on the second time...")
            gfx1 = clij2.push(segmentImp)
            gfx2 = clij2.create(gfx1)
            gfx3 = clij2.create(gfx1)
            gfx4 = clij2.create(gfx1)
            gfx5 = clij2.create(gfx1)
            gfx7 = clij2.create([imp.getWidth(), imp.getHeight()])
        except:
            errorDialog(
                """Could not send image to graphics card, it may be too large!
		
			Easy solutions: Try	processing as 8-bit, cropping or scaling the image, or
			select a different CLIJ2 GPU.

			This issue is often intermittent, so trying again may also work! 

			See the "Big Images on x graphics cards' notes at:
			https://clij2.github.io/clij2-docs/troubleshooting for more solutions
			
			""" + str(clij2.reportMemory()))

    gfx1, gfx2, gfx3, gfx4, gfx5 = segment(gfx1, gfx2, gfx3, gfx4, gfx5,
                                           gaussianSigma, thresholdMethod,
                                           maxIntensity, largeDoGSigma,
                                           pixelAspect, originalTitle, topHat,
                                           topHatSigma, manualSegment,
                                           manualThreshold)
    clij2.maximumZProjection(gfx5, gfx7)

    labelPrevImp = clij2.pull(gfx7)
    IJ.setMinAndMax(labelPrevImp, 0, clij2.getMaximumOfAllPixels(gfx7))
    labelPrevImp.setTitle("Preview segmentation")
    labelPrevImp.show()

    IJ.run("glasbey_inverted")

    while ((not gd.wasCanceled()) and not (gd.wasOKed())):

        segmentChannel = int(choices.get(0).getSelectedItem())
        quantChannel = int(choices.get(1).getSelectedItem())
        thresholdMethod = choices.get(2).getSelectedItem()
        maxIntensity = int(choices.get(3).getSelectedItem())
        gaussianSigma = sliders.get(0).getValue() / 10.0
        largeDoGSigma = gd.sliders.get(1).getValue() / 10.0
        topHat = gd.checkboxes.get(0).getState()
        topHatSigma = gd.sliders.get(2).getValue() / 10.0

        manualSegment = gd.checkboxes.get(1).getState()
        manualThreshold = gd.sliders.get(3).getValue()

        if (segmentChannelOld != segmentChannel
                or thresholdMethodOld != thresholdMethod
                or maxIntensityOld != maxIntensity
                or gaussianSigmaOld != gaussianSigma
                or largeDoGSigmaOld != largeDoGSigma or topHatOld != topHat
                or topHatSigmaOld != topHatSigma
                or manualSegmentOld != manualSegment
                or manualThresholdOld != manualThreshold):

            if segmentChannelOld != segmentChannel:
                clij2.clear()
                segmentImp = extractChannel(imp1, segmentChannel, 0)
                gfx1 = clij2.push(segmentImp)
                gfx2 = clij2.create(gfx1)
                gfx3 = clij2.create(gfx1)
                gfx4 = clij2.create(gfx1)
                gfx5 = clij2.create(gfx1)
                gfx7 = clij2.create([imp.getWidth(), imp.getHeight()])
            gfx1, gfx2, gfx3, gfx4, gfx5 = segment(
                gfx1, gfx2, gfx3, gfx4, gfx5, gaussianSigma, thresholdMethod,
                maxIntensity, largeDoGSigma, pixelAspect, originalTitle,
                topHat, topHatSigma, manualSegment, manualThreshold)
            clij2.maximumZProjection(gfx5, gfx7)
            labelPrevImp.close()
            labelPrevImp = clij2.pull(gfx7)
            IJ.setMinAndMax(labelPrevImp, 0, clij2.getMaximumOfAllPixels(gfx7))
            labelPrevImp.setTitle("Preview segmentation")
            labelPrevImp.show()

            IJ.run("glasbey_inverted")

        segmentChannelOld = segmentChannel
        thresholdMethodOld = thresholdMethod
        maxIntensityOld = maxIntensity
        gaussianSigmaOld = gaussianSigma
        largeDoGSigmaOld = largeDoGSigma
        topHatOld = topHat
        topHatSigmaOld = topHatSigma

        manualSegmentOld = manualSegment
        manualThresholdOld = manualThreshold

        Thread.sleep(200)
    labelPrevImp.close()

    return segmentChannel, quantChannel, thresholdMethod, maxIntensity, gaussianSigma, largeDoGSigma, topHat, topHatSigma, manualSegment, manualThreshold
# Advanced options
gd.setInsets(25,100,10)
gd.addMessage("Advanced Options:",font)
advancedoptionsf=gd.getMessage()

ncores=Runtime.getRuntime().availableProcessors()
defaultCores=1
if ncores >=8:
    defaultCores=4
elif ncores>=4:
    defaultCores=2
gd.addSlider("Number of cpu cores to use",1,ncores,defaultCores)

gd.setInsets(0,230,10)
gd.addCheckbox("Verbose log messages",False)

gd.addStringField("Output folder suffix","",20)
outsuffixf = gd.getStringFields().get(3)

gd.addStringField("(Further) Registration Params","",50);
regparamf = gd.getStringFields().get(4)
gd.addStringField("Additional Arguments to munger.pl","",50);

regrootf.addTextListener(RegRootListener())
imgdirf.addTextListener(ImageDirListener())
outsuffixf.addTextListener(OuputSuffixListener())
choicef.addItemListener(RegParamListener())
# used for errors etc
gd.addMessage("Start by choosing a registration directory or images directory!")
statusf=gd.getMessage()
Exemple #16
0
- matchTemplate Method limited to normalised method to have correlation map in range 0-1 : easier to apply a treshold.  

The search region can be limited to a rectangular ROI, that is drawn on the image/stack before execution of the plugin.

Requirements:
- IJ-OpenCV update site
'''
#import time
#@PrefService prefs
from fiji.util.gui import GenericDialogPlus

## Create GUI
Win = GenericDialogPlus("Multiple Template Matching")
Win.addImageChoice("Template", prefs.get("Template", "Choice"))
Win.addImageChoice("Image", prefs.get("Image", "Choice"))
Win.addCheckbox("Flip_template_vertically", prefs.getInt("FlipV", False))
Win.addCheckbox("Flip_template_horizontally", prefs.getInt("FlipH", False))
Win.addStringField("Rotate template by ..(comma-separated)",
                   prefs.get("Angles", ""))
Win.addChoice("Matching_method", [
    "Normalised Square Difference", "Normalised cross-correlation",
    "Normalised 0-mean cross-correlation"
], prefs.get("Method", "Normalised 0-mean cross-correlation"))
Win.addNumericField("Number_of_templates expected", prefs.getInt("N_hit", 1),
                    0)
Win.addMessage("If more than 1 template expected :")
Win.addNumericField("Score_Threshold [0-1]",
                    prefs.getFloat("Score_Threshold", 0.5), 2)
#Win.addNumericField("Min_peak_height relative to neighborhood ([0-1], decrease to get more hits)", prefs.getFloat("Tolerance",0.1), 2)
Win.addNumericField("Maximal_overlap between Bounding boxes [0-1]",
                    prefs.getFloat("MaxOverlap", 0.4), 2)
Exemple #17
0
    # Advanced options
    gd.setInsets(25, 100, 10)
    gd.addMessage("Advanced Options:", font)
    advancedoptionsf = gd.getMessage()

    ncores = Runtime.getRuntime().availableProcessors()
    defaultCores = 1
    if ncores >= 8:
        defaultCores = 4
    elif ncores >= 4:
        defaultCores = 2
    gd.addSlider("Number of cpu cores to use", 1, ncores, defaultCores)

    gd.setInsets(0, 230, 10)
    gd.addCheckbox("Verbose log messages", False)

    gd.addStringField("Output folder suffix", "", 20)
    outsuffixf = gd.getStringFields().get(3)

    gd.addStringField("(Further) Registration Params", "", 50)
    regparamf = gd.getStringFields().get(4)
    gd.addStringField("Additional Arguments to munger.pl", "", 50)

    regrootf.addTextListener(RegRootListener())
    imgdirf.addTextListener(ImageDirListener())
    outsuffixf.addTextListener(OuputSuffixListener())
    choicef.addItemListener(RegParamListener())
    # used for errors etc
    gd.addMessage(
        "Start by choosing a registration directory or images directory!")