Java Code Examples for ij.gui.GenericDialog#getNextBoolean()

The following examples show how to use ij.gui.GenericDialog#getNextBoolean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GeometricHashing.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean parseDialog( final GenericDialog gd, final RegistrationType registrationType )
{
	model = new TransformationModel( defaultModel = gd.getNextChoiceIndex() );
	
	if ( defaultRegularize = gd.getNextBoolean() )
	{
		if ( !model.queryRegularizedModel() )
			return false;
	}

	final float maxEpsilon = RANSACParameters.max_epsilon = (float)gd.getNextNumber();
	final float ratioOfDistance = GeometricHashingParameters.ratioOfDistance = (float)gd.getNextNumber();

	this.ransacParams = new RANSACParameters( maxEpsilon, RANSACParameters.min_inlier_ratio, RANSACParameters.min_inlier_factor, RANSACParameters.num_iterations );
	this.ghParams = new GeometricHashingParameters( GeometricHashingParameters.differenceThreshold, ratioOfDistance, GeometricHashingParameters.useAssociatedBeads );

	return true;
}
 
Example 2
Source File: LabelToRgbPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void run(String arg)
{
	ImagePlus imagePlus = IJ.getImage();

	int maxLabel = computeMaxLabel(imagePlus);
	
	// Create a new generic dialog with appropriate options
   	GenericDialog gd = new GenericDialog("Labels To RGB");
   	gd.addChoice("Colormap", CommonLabelMaps.getAllLabels(), 
   			CommonLabelMaps.GOLDEN_ANGLE.getLabel());
   	gd.addChoice("Background", CommonColors.getAllLabels(), CommonColors.WHITE.getLabel());
   	gd.addCheckbox("Shuffle", true);
   	gd.showDialog();
	
   	// test cancel  
   	if (gd.wasCanceled()) 
   		return;

   	// Create a new LUT from info in dialog
	String lutName = gd.getNextChoice();
	String bgColorName = gd.getNextChoice();
	Color bgColor = CommonColors.fromLabel(bgColorName).getColor();
	boolean shuffleLut = gd.getNextBoolean();

	// Create a new LUT from info in dialog
	byte[][] lut = CommonLabelMaps.fromLabel(lutName).computeLut(maxLabel, shuffleLut);
   	
	// Create a new RGB image from index image and LUT options
	ImagePlus resPlus = LabelImages.labelToRgb(imagePlus, lut, bgColor);
   	
	// dispay result image
	resPlus.copyScale(imagePlus);
	resPlus.show();
   	if (imagePlus.getStackSize() > 1) 
   	{
   		resPlus.setSlice(imagePlus.getCurrentSlice());
   	}
}
 
Example 3
Source File: FlipAxesCommand.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run()
{
	// load SpimData
	final LoadParseQueryXML result = new LoadParseQueryXML();
	if ( !result.queryXML( "to load a TileConfiguration for", false, false, false, false, false ) )
		return;
	final SpimData2 data = result.getData();
	final ArrayList< ViewId > views = SpimData2.getAllViewIdsSorted( result.getData(),
			result.getViewSetupsToProcess(), result.getTimePointsToProcess() );

	final Map< ViewId, Dimensions > dims = new HashMap<>();
	views.forEach( v -> dims.put( v,
			data.getSequenceDescription().getViewDescriptions().get( v ).getViewSetup().getSize() ) );
	final boolean[] flipAxes = new boolean[3];
	GenericDialog gd = new GenericDialog( "Flip Parameters" );
	gd.addCheckbox( "Flip_X", true );
	gd.addCheckbox( "Flip_Y", false );
	gd.addCheckbox( "Flip_Z", false );

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

	flipAxes[0] = gd.getNextBoolean();
	flipAxes[1] = gd.getNextBoolean();
	flipAxes[2] = gd.getNextBoolean();

	FlipAxes.applyFlipToData( data.getViewRegistrations(), dims, views, flipAxes );

	// save result
	SpimData2.saveXML( data, result.getXMLFileName(), result.getClusterExtension() );

}
 
Example 4
Source File: Toggle_Cluster_Options.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run( String arg0 )
{
	final GenericDialog gd = new GenericDialog( "Toggle Cluster Processing Options" );
	gd.addCheckbox( "Display_Cluster Processing Options", displayClusterProcessing );
	gd.showDialog();

	if ( gd.wasCanceled() )
		return;

	displayClusterProcessing = gd.getNextBoolean();

	IOFunctions.println( "Cluster processing option: " + ( displayClusterProcessing ? "ON" : "OFF" ) );
}
 
Example 5
Source File: ExportToRenderAsIs_Plugin.java    From render with GNU General Public License v2.0 5 votes vote down vote up
boolean setParametersFromDialog() {

            final GenericDialog dialog = new GenericDialog("Export Parameters");

            final int defaultTextColumns = 100;
            dialog.addStringField("Render Web Services Base URL", baseDataUrl, defaultTextColumns);
            layerRange.addFieldsToDialog(dialog);
            dialog.addCheckbox("Only Export Visible Patches", onlyExportVisiblePatches);
            dialog.addCheckbox("Use Patch Title For Tile ID", usePatchTitleForTileId);
            dialog.addMessage("  note: leave unchecked to use TrakEM2 patch object ID as tile ID");
            dialog.addStringField("Target Render Stack Owner", targetRenderOwner, defaultTextColumns);
            dialog.addStringField("Target Render Stack Project", targetRenderProject, defaultTextColumns);
            dialog.addStringField("Target Render Stack Name", targetRenderStack, defaultTextColumns);
            dialog.addNumericField("Stack Resolution X (nm/pixel)", stackResolutionX, 0);
            dialog.addNumericField("Stack Resolution Y (nm/pixel)", stackResolutionY, 0);
            dialog.addNumericField("Stack Resolution Z (nm/pixel)", stackResolutionZ, 0);
            dialog.addCheckbox("Complete Stack After Export", completeStackAfterExport);

            dialog.showDialog();
            dialog.repaint(); // seems to help with missing dialog elements, but shouldn't be necessary

            final boolean wasCancelled = dialog.wasCanceled();

            if (! wasCancelled) {
                baseDataUrl = dialog.getNextString().trim();
                layerRange.setFieldsFromDialog(dialog);
                onlyExportVisiblePatches = dialog.getNextBoolean();
                usePatchTitleForTileId = dialog.getNextBoolean();
                targetRenderOwner = dialog.getNextString().trim();
                targetRenderProject = dialog.getNextString().trim();
                targetRenderStack =  dialog.getNextString().trim();
                stackResolutionX = dialog.getNextNumber();
                stackResolutionY = dialog.getNextNumber();
                stackResolutionZ = dialog.getNextNumber();
                completeStackAfterExport = dialog.getNextBoolean();
            }

            return wasCancelled;
        }
 
Example 6
Source File: GlobalOptimizationParameters.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
public static GlobalOptimizationParameters askUserForParameters(boolean askForGrouping)
{
	// ask user for parameters
	final GenericDialog gd = new GenericDialog("Global optimization options");
	gd.addChoice( "Global_optimization_strategy", methodDescriptions, methodDescriptions[ defaultGlobalOpt ] );
	gd.addNumericField( "relative error threshold", 2.5, 3 );
	gd.addNumericField( "absolute error threshold", 3.5, 3 );
	if (askForGrouping )
		gd.addCheckbox( "show_expert_grouping_options", defaultExpertGrouping );
	gd.showDialog();

	if (gd.wasCanceled())
		return null;

	final double relTh = gd.getNextNumber();
	final double absTh = gd.getNextNumber();
	final int methodIdx = defaultGlobalOpt = gd.getNextChoiceIndex();
	final boolean expertGrouping = askForGrouping ? gd.getNextBoolean() : false;

	final GlobalOptType method;
	if (methodIdx == 0)
		method = GlobalOptType.SIMPLE;
	else if (methodIdx == 1)
		method = GlobalOptType.ITERATIVE;
	else
		method = GlobalOptType.TWO_ROUND;

	return new GlobalOptimizationParameters(relTh, absTh, method, expertGrouping);
}
 
Example 7
Source File: FlipAxesPopup.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e)
{
	final SpimData spimData = (SpimData)panel.getSpimData();
	final List< ViewId > views = ((GroupedRowWindow) panel).selectedRowsViewIdGroups().stream().reduce(new ArrayList<>(),  (a,b) -> {a.addAll( b ); return a;} );

	final Map<ViewId, Dimensions> dims = new HashMap<>();
	views.forEach( v -> dims.put( v, spimData.getSequenceDescription().getViewDescriptions() .get( v ).getViewSetup().getSize()) );
	final boolean[] flipAxes = new boolean[3];
	GenericDialog gd = new GenericDialog( "Flip Parameters" );
	gd.addCheckbox( "Flip X", true );
	gd.addCheckbox( "Flip Y", false );
	gd.addCheckbox( "Flip Z", false );

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

	flipAxes[0] = gd.getNextBoolean();
	flipAxes[1] = gd.getNextBoolean();
	flipAxes[2] = gd.getNextBoolean();

	FlipAxes.applyFlipToData( spimData.getViewRegistrations(), dims, views, flipAxes );

	panel.updateContent();
	panel.bdvPopup().updateBDV();
}
 
Example 8
Source File: ExportToRenderUsingBasisStack_Plugin.java    From render with GNU General Public License v2.0 5 votes vote down vote up
boolean setParametersFromDialog() {

            final GenericDialog dialog = new GenericDialog("Export Parameters");

            final int defaultTextColumns = 100;
            dialog.addStringField("Render Web Services Base URL", baseDataUrl, defaultTextColumns);
            dialog.addStringField("Basis Render Stack Owner", basisRenderOwner, defaultTextColumns);
            dialog.addStringField("Basis Render Stack Project", basisRenderProject, defaultTextColumns);
            dialog.addStringField("Basis Render Stack Name", basisRenderStack, defaultTextColumns);
            layerRange.addFieldsToDialog(dialog);
            dialog.addStringField("Target Render Stack Owner", targetRenderOwner, defaultTextColumns);
            dialog.addStringField("Target Render Stack Project", targetRenderProject, defaultTextColumns);
            dialog.addStringField("Target Render Stack Name", targetRenderStack, defaultTextColumns);
            dialog.addStringField("TrakEM2 Z to Target Z Map", trakZToTargetZMapString, defaultTextColumns);
            dialog.addMessage("  note: leave empty to skip mapping, format is a=b,c=d");
            dialog.addCheckbox("Complete Stack After Export", completeStackAfterExport);

            dialog.showDialog();
            dialog.repaint(); // seems to help with missing dialog elements, but shouldn't be necessary

            final boolean wasCancelled = dialog.wasCanceled();

            if (! wasCancelled) {
                baseDataUrl = dialog.getNextString().trim();
                basisRenderOwner = dialog.getNextString().trim();
                basisRenderProject = dialog.getNextString().trim();
                basisRenderStack =  dialog.getNextString().trim();
                layerRange.setFieldsFromDialog(dialog);
                targetRenderOwner = dialog.getNextString().trim();
                targetRenderProject = dialog.getNextString().trim();
                targetRenderStack =  dialog.getNextString().trim();
                trakZToTargetZMapString =  dialog.getNextString().trim();
                completeStackAfterExport = dialog.getNextBoolean();

                sectionIdToDataMap.clear();
                trakZToTargetZMap.clear();
            }

            return wasCancelled;
        }
 
Example 9
Source File: RegionAdjacencyGraphPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void run(String arg0)
{
	ImagePlus imagePlus = IJ.getImage();
	
	boolean isPlanar = imagePlus.getStackSize() == 1;
	boolean showRAG = false;
	ImagePlus targetPlus = imagePlus;

	if (isPlanar)
	{
		// create the list of image names
		int[] indices = WindowManager.getIDList();
		String[] imageNames = new String[indices.length];
		for (int i = 0; i < indices.length; i++)
		{
			imageNames[i] = WindowManager.getImage(indices[i]).getTitle();
		}
		
		// name of selected image
		String selectedImageName = IJ.getImage().getTitle();

		GenericDialog gd = new GenericDialog("Region Adjacency Graph");
		gd.addCheckbox("Show RAG", true);
		gd.addChoice("Image to overlay", imageNames, selectedImageName);
		
		gd.showDialog();
		if (gd.wasCanceled())
		{
			return;
		}
		
		showRAG = gd.getNextBoolean();
		int targetImageIndex = gd.getNextChoiceIndex();
		targetPlus = WindowManager.getImage(indices[targetImageIndex]);
	}

	Set<LabelPair> adjList = RegionAdjacencyGraph.computeAdjacencies(imagePlus);
	
	if (showRAG)
	{
		overlayRAG(adjList, imagePlus, targetPlus);
	}
	
	ResultsTable table = createTable(adjList);
	String newName = imagePlus.getShortTitle() + "-RAG";
	table.show(newName);
}
 
Example 10
Source File: ParticleAnalysis3DPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void run(String args) 
  {
      ImagePlus imagePlus = IJ.getImage();
      
if (imagePlus.getStackSize() == 1) 
{
	IJ.error("Requires a Stack");
	return;
}

      // create the dialog, with operator options
      GenericDialog gd = new GenericDialog("Particles Analysis 3D");
      gd.addCheckbox("Volume", true);
      gd.addCheckbox("Surface Area", true);
      gd.addCheckbox("Sphericity", true);
      gd.addCheckbox("Euler Number", true);
      gd.addCheckbox("Equivalent Ellipsoid", true);
      gd.addCheckbox("Ellipsoid Elongation", true);
      gd.addCheckbox("Max. Inscribed Ball", true);
      gd.addMessage("");
      gd.addChoice("Surface area method:", surfaceAreaMethods, surfaceAreaMethods[1]);
      gd.addChoice("Euler Connectivity:", connectivityNames, connectivityNames[1]);
      gd.showDialog();
      
      // If cancel was clicked, do nothing
      if (gd.wasCanceled())
          return;

      // Extract features to extract from image
      computeVolume 		= gd.getNextBoolean();
      computeSurface 		= gd.getNextBoolean();
      computeSphericity 	= gd.getNextBoolean() & computeVolume & computeSurface;
      computeEulerNumber	= gd.getNextBoolean();
      computeEllipsoid 	= gd.getNextBoolean();
      computeElongations 	= gd.getNextBoolean() & computeEllipsoid;
      computeInscribedBall = gd.getNextBoolean();
      
      
      // extract analysis options
      surfaceAreaDirs = dirNumbers[gd.getNextChoiceIndex()];
      connectivity = connectivityValues[gd.getNextChoiceIndex()];
      
      // Execute the plugin
      ResultsTable table = process(imagePlus);
      
	// create string for indexing results
String tableName = imagePlus.getShortTitle() + "-morpho"; 
  
// show result
table.show(tableName);
  }
 
Example 11
Source File: DistanceTransformWatershed3D.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Plugin run method
 */
public void run(String arg) {
	
	ImagePlus image = WindowManager.getCurrentImage();
	if ( image == null ) 
	{
		IJ.error("Distance Transform Watershed 3D",
				"Need at least one image to work");
		return;
	}

	if( !BinaryImages.isBinaryImage( image ) )
	{
		IJ.error( "Distance Transform Watershed 3D", "Input image is not"
				+ " binary (8-bit with only 0 or 255 values)" );
	}

	// Create a new generic dialog with appropriate options
	GenericDialog gd = new GenericDialog( "Distance Transform Watershed 3D" );
	gd.setInsets( 0, 0, 0 );
	gd.addMessage( "Distance map options:",
			new Font( "SansSerif", Font.BOLD, 12 ) );
	gd.addChoice( "Distances", ChamferWeights3D.getAllLabels(), weightLabel );
	String[] outputTypes = new String[]{"32 bits", "16 bits"};
	gd.addChoice( "Output Type", outputTypes, outputTypes[ floatProcessing ? 0:1 ]);
	gd.setInsets( 0, 0, 0 );
	gd.addCheckbox( "Normalize weights", normalize );
	gd.setInsets( 20, 0, 0 );
	gd.addMessage( "Watershed options:",
			new Font( "SansSerif", Font.BOLD, 12 ) );
	gd.addNumericField( "Dynamic", dynamic, 2 );
	gd.addChoice( "Connectivity", Conn3D.getAllLabels(),
			connectivity.label );
	gd.addHelp( "http://imagej.net/MorphoLibJ#Utilities_for_binary_images" );
	gd.showDialog();

	// test cancel
	if ( gd.wasCanceled() )
		return;

	// set up current parameters
	weightLabel = gd.getNextChoice();
	floatProcessing = gd.getNextChoiceIndex() == 0;
	normalize = gd.getNextBoolean();
	dynamic = (int) gd.getNextNumber();
	connectivity = Conn3D.fromLabel( gd.getNextChoice() );

	// identify which weights should be used
	weights = ChamferWeights3D.fromLabel( weightLabel );

	long t0 = System.currentTimeMillis();

	final ImagePlus result;
	if (floatProcessing)
		result = processFloat( image, weights.getFloatWeights(), normalize );
	else
		result = processShort( image, weights.getShortWeights(), normalize );

	Images3D.optimizeDisplayRange( result );

	// Display the result image
	result.show();
	result.setSlice( image.getCurrentSlice() );

	// Display elapsed time
	long t1 = System.currentTimeMillis();
	IJUtils.showElapsedTime( "Distance Transform Watershed 3D",
			t1 - t0, image );
}
 
Example 12
Source File: ImportFromRender_Plugin.java    From render with GNU General Public License v2.0 4 votes vote down vote up
boolean setParametersFromDialog() {

            final GenericDialog dialog = new GenericDialog("Import Parameters");

            final int defaultTextColumns = 80;
            dialog.addStringField("Render Web Services Base URL", baseDataUrl, defaultTextColumns);
            dialog.addStringField("Render Stack Owner", renderOwner, defaultTextColumns);
            dialog.addStringField("Render Stack Project", renderProject, defaultTextColumns);
            dialog.addStringField("Render Stack Name", renderStack, defaultTextColumns);
            dialog.addStringField("Channel (empty for default)", "", defaultTextColumns);
            dialog.addNumericField("Min Z", minZ, 1);
            dialog.addNumericField("Max Z", maxZ, 1);
            dialog.addNumericField("Image Plus Type (use '-1' to slowly derive dynamically)", imagePlusType, 0);
            dialog.addMessage("  note: image plus type values are: 0:GRAY8, 1:GRAY16, 2:GRAY32, 3:COLOR_256, 4:COLOR_RGB");
            dialog.addCheckbox("Load Masks", loadMasks);
            dialog.addCheckbox("Split Sections", splitSections);
            dialog.addCheckbox("Replace Last Transform With Stage", replaceLastWithStage);
            dialog.addNumericField("Number of threads for mipmaps", numberOfMipmapThreads, 0);

            dialog.showDialog();
            dialog.repaint(); // seems to help with missing dialog elements, but shouldn't be necessary

            final boolean wasCancelled = dialog.wasCanceled();

            if (! wasCancelled) {
                baseDataUrl = dialog.getNextString();
                renderOwner = dialog.getNextString();
                renderProject = dialog.getNextString();
                renderStack =  dialog.getNextString();
                String channelString = dialog.getNextString();
                if (channelString != null && channelString.length() > 0) {
                    channels.add(channelString);
                }
                minZ = dialog.getNextNumber();
                maxZ = dialog.getNextNumber();
                imagePlusType = new Double(dialog.getNextNumber()).intValue();
                loadMasks = dialog.getNextBoolean();
                splitSections = dialog.getNextBoolean();
                replaceLastWithStage = dialog.getNextBoolean();
                numberOfMipmapThreads = (int) dialog.getNextNumber();
            }

            return wasCancelled;
        }
 
Example 13
Source File: MorphologicalFilterCross3DPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
	public void run(String arg) {
		ImagePlus imagePlus = WindowManager.getCurrentImage();
		if (imagePlus == null) {
			IJ.error("No image", "Need at least one image to work");
			return;
		}
		
		// create the dialog
		GenericDialog gd = new GenericDialog("Morphological Filter");
		
		gd.addChoice("Operation", Operation.getAllLabels(), 
				Operation.DILATION.toString());
		gd.addCheckbox("Show Element", false);
		
		// Could also add an option for the type of operation
		gd.showDialog();
		
		if (gd.wasCanceled())
			return;
		
		long t0 = System.currentTimeMillis();

		// extract chosen parameters
		Operation op = Operation.fromLabel(gd.getNextChoice());
		boolean showStrel = gd.getNextBoolean();
		
		// Create structuring element of the given size
		Strel3D strel = new Cross3DStrel();
		strel.showProgress(true);
		
		// Eventually display the structuring element used for processing 
		if (showStrel) {
			showStrelImage(strel);
		}
		
		// Execute core of the plugin
		ImagePlus resPlus = process(imagePlus, op, strel);

		if (resPlus == null)
			return;

		// Display the result image
		resPlus.show();
		resPlus.setSlice(imagePlus.getCurrentSlice());

		// Display elapsed time
		long t1 = System.currentTimeMillis();
		IJUtils.showElapsedTime(op.toString(), t1 - t0, imagePlus);
//		IJ.showStatus("Elapsed time: " + (t1 - t0) / 1000. + "s");
	}
 
Example 14
Source File: RemoveBorderLabelsPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void run(String arg0)
{
	ImagePlus imagePlus = IJ.getImage();
	boolean isStack = imagePlus.getStackSize() > 1;
	
	// opens a dialog to choose which borders to remove
	GenericDialog gd = new GenericDialog("Remove Border Labels");
	gd.addCheckbox("Left", true);
	gd.addCheckbox("Right", true);
	gd.addCheckbox("Top", true);
	gd.addCheckbox("Bottom", true);
	if (isStack) 
	{
		gd.addCheckbox("Front", true);
		gd.addCheckbox("Back", true);
	}
	
	gd.showDialog();
	if (gd.wasCanceled())
	{
		return;
	}
	
	boolean removeLeft = gd.getNextBoolean();
	boolean removeRight = gd.getNextBoolean();
	boolean removeTop = gd.getNextBoolean();
	boolean removeBottom = gd.getNextBoolean();
	boolean removeFront = false, removeBack = false;
	if (isStack)
	{
		removeFront = gd.getNextBoolean();
		removeBack = gd.getNextBoolean();
	}
	
	IJ.showStatus("Identifies border labels");

	ImagePlus resultPlus = remove( imagePlus, removeLeft, removeRight,
			removeTop, removeBottom, removeFront, removeBack);
	
	// Display with same settings as original image
	resultPlus.show();
	if (isStack)
	{
		resultPlus.setZ(imagePlus.getZ());
		resultPlus.setSlice(imagePlus.getCurrentSlice());
	}
}
 
Example 15
Source File: MaxInscribedCirclePlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
	public void run(String arg0) 
	{
		// Open a dialog to choose:
		// - a label image
		// - a set of weights
		int[] indices = WindowManager.getIDList();
		if (indices==null)
		{
			IJ.error("No image", "Need at least one image to work");
			return;
		}
		
		// create the list of image names
		String[] imageNames = new String[indices.length];
		for (int i=0; i<indices.length; i++)
		{
			imageNames[i] = WindowManager.getImage(indices[i]).getTitle();
		}
		
		// name of selected image
		String selectedImageName = IJ.getImage().getTitle();

		// create the dialog
		GenericDialog gd = new GenericDialog("Max. Inscribed Circle");
		gd.addChoice("Label Image:", imageNames, selectedImageName);
//		// Set Chessknight weights as default
//		gd.addChoice("Distances", ChamferWeights.getAllLabels(), 
//				ChamferWeights.CHESSKNIGHT.toString());
		gd.addCheckbox("Show Overlay Result", true);
		gd.addChoice("Image to overlay:", imageNames, selectedImageName);
		gd.showDialog();
		
		if (gd.wasCanceled())
			return;
		
		// set up current parameters
		int labelImageIndex = gd.getNextChoiceIndex();
		ImagePlus labelImage = WindowManager.getImage(labelImageIndex+1);
//		ChamferWeights weights = ChamferWeights.fromLabel(gd.getNextChoice());
		boolean showOverlay = gd.getNextBoolean();
		int resultImageIndex = gd.getNextChoiceIndex();
		
		// check if image is a label image
		if (!LabelImages.isLabelImageType(labelImage))
		{
            IJ.showMessage("Input image should be a label image");
            return;
        }
        
		// Execute the plugin
    	LargestInscribedCircle op = new LargestInscribedCircle();
		Map<Integer, Circle2D> results = op.analyzeRegions(labelImage);
       
        // Display plugin result as table
		ResultsTable table = op.createTable(results);
		String tableName = labelImage.getShortTitle() + "-MaxInscribedCircle"; 
		table.show(tableName);
		
		// Check if results must be displayed on an image
		if (showOverlay)
		{
			// find image for displaying geometric overlays
			ImagePlus resultImage = WindowManager.getImage(resultImageIndex + 1);
			showResultsAsOverlay(results, resultImage);
		}
	}
 
Example 16
Source File: ICPRefinement.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static boolean getGUIParametersAdvanced( final SpimData2 data, final ICPRefinementParameters params )
{
	//
	// get advanced parameters
	//
	final GenericDialog gd = new GenericDialog( "Expert Refine by ICP" );

	final ArrayList< String > labels = getAllLabels( params.viewIds, data );

	if ( labels.size() == 0 )
	{
		IOFunctions.println( "No interest point defined, please detect interest point and re-run" );
		new Interest_Point_Detection().detectInterestPoints( data, params.viewIds );
		return false;
	}

	final String[] labelChoice = new String[ labels.size() ];

	for ( int i = 0; i < labels.size(); ++i )
		labelChoice[ i ] = labels.get( i );

	if ( defaultLabelDialog >= labelChoice.length )
		defaultLabelDialog = 0;

	gd.addChoice( "Interest_Points", labelChoice, labelChoice[ defaultLabelDialog ] );
	gd.addNumericField( "ICP_maximum_error", defaultICPError, 2 );
	gd.addChoice( "Transformation model", TransformationModelGUI.modelChoice, TransformationModelGUI.modelChoice[ defaultModel ] );
	gd.addCheckbox( "Regularize_model", defaultRegularize );

	final ArrayList< Channel > channels = SpimData2.getAllChannelsSorted( data, params.viewIds );
	final String[] channelChoice = new String[ 2 + channels.size() ];
	channelChoice[ 0 ] = "Do not group";
	channelChoice[ 1 ] = "Group all";
	for ( int i = 0; i < channels.size(); ++i )
		channelChoice[ i + 2 ] = "Only channel " + channels.get( i ).getName();
	if ( defaultChannelChoice >= channelChoice.length )
		defaultChannelChoice = 0;

	gd.addChoice( "Group_channels", channelChoice, channelChoice[ defaultChannelChoice ] );
	gd.addCheckbox( "Group_tiles", false );
	gd.addCheckbox( "Group_illuminations", false );

	gd.showDialog();
	if ( gd.wasCanceled() )
		return false;

	params.label = labels.get( defaultLabelDialog = gd.getNextChoiceIndex() );
	params.maxError = defaultICPError = gd.getNextNumber();
	TransformationModelGUI model = new TransformationModelGUI( defaultModel = gd.getNextChoiceIndex() );

	if ( defaultRegularize = gd.getNextBoolean() )
		if ( !model.queryRegularizedModel() )
			return false;

	params.transformationModel = model.getModel();

	final int channelGroup = gd.getNextChoiceIndex();
	if ( channelGroup > 0 )
	{
		params.groupChannels = true;
		if ( channelGroup >= 2 )
		{
			for ( int i = 0; i < channels.size(); ++i )
			{
				if ( channelGroup - 2 != i )
					params.doNotGroupChannels.add( channels.get( i ).getId() );
				else
					IOFunctions.println( "Only grouping tiles & illuminations for channel: " + channels.get( i ).getName() );
			}
		}
	}
	else
	{
		params.groupChannels = false;
	}
	params.groupTiles = gd.getNextBoolean();
	params.groupIllums = gd.getNextBoolean();

	params.transformationDescription = "Expert ICP Refinement";

	return true;
}
 
Example 17
Source File: AnalyzeMicrostructure3D.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void run(String arg)
{
    ImagePlus imagePlus = IJ.getImage();
    
    if (imagePlus.getStackSize() == 1) 
    {
        IJ.error("Requires a Stack");
        return;
    }
    
    // create the dialog, with operator options
    GenericDialog gd = new GenericDialog("Microstructure Analysis");
    gd.addCheckbox("Volume", true);
    gd.addCheckbox("Surface Area", true);
    gd.addCheckbox("Mean_Breadth", true);
    gd.addCheckbox("Euler Number", true);
    gd.addMessage("");
    gd.addChoice("Surface area method:", dirNumberLabels, dirNumberLabels[1]);
    gd.addChoice("Mean breadth method:", dirNumberLabels, dirNumberLabels[1]);
    gd.addChoice("Mean Breadth Conn.:", connectivity2dNames, connectivity2dNames[1]);
    gd.addChoice("Euler Connectivity:", connectivity3dNames, connectivity3dNames[1]);
    gd.showDialog();
    
    // If cancel was clicked, do nothing
    if (gd.wasCanceled())
        return;

    // Extract features to extract from image
    computeVolume       = gd.getNextBoolean();
    computeSurface      = gd.getNextBoolean();
    computeMeanBreadth  = gd.getNextBoolean();
    computeEulerNumber  = gd.getNextBoolean();
    
    // extract analysis options
    surfaceAreaDirs = dirNumbers[gd.getNextChoiceIndex()];
    meanBreadthDirs = dirNumbers[gd.getNextChoiceIndex()];
    connectivity2d = connectivity2dValues[gd.getNextChoiceIndex()];
    connectivity = connectivity3dValues[gd.getNextChoiceIndex()];
    
    // Execute the plugin
    ResultsTable table = process(imagePlus);
    
    // create string for indexing results
    String tableName = imagePlus.getShortTitle() + "-microstructure"; 

    // show result
    table.show(tableName);
}
 
Example 18
Source File: GeodesicDistanceMap3DPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
	public void run(String arg0)
	{
		// Open a dialog to choose:
		// - marker image
		// - mask image
		// - set of weights
		int[] indices = WindowManager.getIDList();
		if (indices == null)
		{
			IJ.error("No image", "Need at least one image to work");
			return;
		}

		// create the list of image names
		String[] imageNames = new String[indices.length];
		for (int i = 0; i < indices.length; i++)
		{
			imageNames[i] = WindowManager.getImage(indices[i]).getTitle();
		}

		// create the dialog
		GenericDialog gd = new GenericDialog("Geodesic Distance Map 3D");

		gd.addChoice("Marker Image", imageNames, IJ.getImage().getTitle());
		gd.addChoice("Mask Image", imageNames, IJ.getImage().getTitle());
		// Set default weights
		gd.addChoice("Distances", ChamferWeights3D.getAllLabels(),
				ChamferWeights3D.WEIGHTS_3_4_5_7.toString());
//		String[] outputTypes = new String[] { "32 bits", "16 bits" };
//		gd.addChoice("Output Type", outputTypes, outputTypes[0]);
		gd.addCheckbox("Normalize weights", true);

		gd.showDialog();

		if (gd.wasCanceled())
			return;

		// set up current parameters
		int markerImageIndex = gd.getNextChoiceIndex();
		ImagePlus markerImage = WindowManager.getImage(markerImageIndex + 1);
		int maskImageIndex = gd.getNextChoiceIndex();
		ImagePlus maskImage = WindowManager.getImage(maskImageIndex + 1);
		String weightLabel = gd.getNextChoice();
		
		// identify which weights should be used
		ChamferWeights3D weights = ChamferWeights3D.fromLabel(weightLabel);
//		boolean resultAsFloat = gd.getNextChoiceIndex() == 0;
		boolean normalizeWeights = gd.getNextBoolean();

		// check image types
		if (markerImage.getType() != ImagePlus.GRAY8)
		{
			IJ.showMessage("Marker image should be binary");
			return;
		}
		if (maskImage.getType() != ImagePlus.GRAY8)
		{
			IJ.showMessage("Mask image should be binary");
			return;
		}

		// Execute core of the plugin
		String newName = createResultImageName(maskImage);
		ImagePlus res;
//		if (resultAsFloat)
//		{
			res = process(markerImage, maskImage, newName,
					weights.getFloatWeights(), normalizeWeights);
//		} else
//		{
//			res = process(markerImage, maskImage, newName,
//					weights.getShortWeights(), normalizeWeights);
//		}

		res.show();
	}
 
Example 19
Source File: ThresholderOrbit.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
public void applyThreshold(ImagePlus imp) {
	imp.deleteRoi();
	ImageProcessor ip = imp.getProcessor();
	ip.resetBinaryThreshold();
	int type = imp.getType();
	if (type==ImagePlus.GRAY16 || type==ImagePlus.GRAY32) {
		applyShortOrFloatThreshold(imp);
		return;
	}
	if (!imp.lock()) return;
	double saveMinThreshold = ip.getMinThreshold();
	double saveMaxThreshold = ip.getMaxThreshold();
	autoThreshold = saveMinThreshold==ImageProcessor.NO_THRESHOLD;

	boolean useBlackAndWhite = true;
	boolean noArgMacro =IJ.macroRunning() && Macro.getOptions()==null;
	if (skipDialog)
		fill1 = fill2 = useBlackAndWhite = true;
	else if (!(autoThreshold||noArgMacro)) {
		GenericDialog gd = new GenericDialog("Make Binary");
		gd.addCheckbox("Thresholded pixels to foreground color", fill1);
		gd.addCheckbox("Remaining pixels to background color", fill2);
		gd.addMessage("");
		gd.addCheckbox("Black foreground, white background", useBW);
		gd.showDialog();
		if (gd.wasCanceled())
		{imp.unlock(); return;}
		fill1 = gd.getNextBoolean();
		fill2 = gd.getNextBoolean();
		useBW = useBlackAndWhite = gd.getNextBoolean();
	} else {
		fill1 = fill2 = true;
		convertToMask = true;
	}

	if (type!=ImagePlus.GRAY8)
		convertToByte(imp);
	ip = imp.getProcessor();

	if (autoThreshold)
		autoThreshold(ip);
	else {
		if (Recorder.record && !Recorder.scriptMode() && (!IJ.isMacro()||Recorder.recordInMacros))
			Recorder.record("setThreshold", (int)saveMinThreshold, (int)saveMaxThreshold);
		minThreshold = saveMinThreshold;
		maxThreshold = saveMaxThreshold;
	}

	if (convertToMask && ip.isColorLut())
		ip.setColorModel(ip.getDefaultColorModel());
	int fcolor, bcolor;
	ip.resetThreshold();
	int savePixel = ip.getPixel(0,0);
	if (useBlackAndWhite)
		ip.setColor(Color.black);
	else
		ip.setColor(Toolbar.getForegroundColor());
	ip.drawPixel(0,0);
	fcolor = ip.getPixel(0,0);
	if (useBlackAndWhite)
		ip.setColor(Color.white);
	else
		ip.setColor(Toolbar.getBackgroundColor());
	ip.drawPixel(0,0);
	bcolor = ip.getPixel(0,0);
	ip.setColor(Toolbar.getForegroundColor());
	ip.putPixel(0,0,savePixel);

	int[] lut = new int[256];
	for (int i=0; i<256; i++) {
		if (i>=minThreshold && i<=maxThreshold)
			lut[i] = fill1?fcolor:(byte)i;
		else {
			lut[i] = fill2?bcolor:(byte)i;
		}
	}
	if (imp.getStackSize()>1)
		new StackProcessor(imp.getStack(), ip).applyTable(lut);
	else
		ip.applyTable(lut);
	if (convertToMask) {
		if (!imp.isInvertedLut()) {
			setInvertedLut(imp);
			fcolor = 255 - fcolor;
			bcolor = 255 - bcolor;
		}
		if (Prefs.blackBackground)
			ip.invertLut();
	}
	if (fill1 && fill2 && ((fcolor==0&&bcolor==255)||(fcolor==255&&bcolor==0)))
		imp.getProcessor().setThreshold(fcolor, fcolor, ImageProcessor.NO_LUT_UPDATE);
	imp.updateAndRepaintWindow();
	imp.unlock();
}
 
Example 20
Source File: DistortionCorrectionTask.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
public boolean setup( final Selection selection )
{
	if ( !setupSIFT( "Distortion Correction: " ) )
		return false;

	/* Geometric filters */

	final GenericDialog gd = new GenericDialog( "Distortion Correction: Geometric filters" );

	gd.addNumericField( "maximal_alignment_error :", maxEpsilon, 2, 6, "px" );
	gd.addNumericField( "minimal_inlier_ratio :", minInlierRatio, 2 );
	gd.addNumericField( "minimal_number_of_inliers :", minNumInliers, 0 );
	gd.addChoice( "expected_transformation :", Param.modelStrings, Param.modelStrings[ expectedModelIndex ] );
	gd.addCheckbox( "test_multiple_hypotheses", multipleHypotheses );
	gd.addCheckbox( "ignore constant background", rejectIdentity );
	gd.addNumericField( "tolerance :", identityTolerance, 2, 6, "px" );
	gd.addCheckbox( "tiles are rougly in place", tilesAreInPlace );

	gd.showDialog();

	if ( gd.wasCanceled() )
		return false;

	maxEpsilon = ( float )gd.getNextNumber();
	minInlierRatio = ( float )gd.getNextNumber();
	minNumInliers = ( int )gd.getNextNumber();
	expectedModelIndex = gd.getNextChoiceIndex();
	multipleHypotheses = gd.getNextBoolean();
	rejectIdentity = gd.getNextBoolean();
	identityTolerance = ( float )gd.getNextNumber();
	tilesAreInPlace = gd.getNextBoolean();

	final GenericDialog gdOptimize = new GenericDialog( "Distortion Correction: Montage Optimization" );
	gdOptimize.addChoice( "desired_transformation :", modelStrings, modelStrings[ desiredModelIndex ] );
	gdOptimize.addCheckbox( "regularize_model", regularize );
	gdOptimize.addMessage( "Optimization:" );
	gdOptimize.addNumericField( "maximal_iterations :", maxIterationsOptimize, 0 );
	gdOptimize.addNumericField( "maximal_plateauwidth :", maxPlateauwidthOptimize, 0 );

	gdOptimize.showDialog();

	if ( gdOptimize.wasCanceled() )
		return false;

	desiredModelIndex = gdOptimize.getNextChoiceIndex();
	regularize = gdOptimize.getNextBoolean();
	maxIterationsOptimize = ( int )gdOptimize.getNextNumber();
	maxPlateauwidthOptimize = ( int )gdOptimize.getNextNumber();

	if ( regularize )
	{
		final GenericDialog gdRegularize = new GenericDialog( "Distortion Correction: Montage Regularization" );

		gdRegularize.addChoice( "regularizer :", modelStrings, modelStrings[ regularizerIndex ] );
		gdRegularize.addNumericField( "lambda :", lambdaRegularize, 2 );

		gdRegularize.showDialog();

		if ( gdRegularize.wasCanceled() )
			return false;

		regularizerIndex = gdRegularize.getNextChoiceIndex();
		lambdaRegularize = gdRegularize.getNextNumber();
	}

	final GenericDialog gdLens = new GenericDialog( "Distortion Correction: Lens Distortion" );

	gdLens.addMessage( "Lens Model :" );
	gdLens.addNumericField( "power_of_polynomial_kernel :", dimension, 0 );
	gdLens.addNumericField( "lambda :", lambda, 6 );

	gdLens.addMessage( "Apply Distortion Correction :" );

	Utils.addLayerRangeChoices( selection.getLayer(), gdLens );
	gdLens.addCheckbox( "clear_present_transforms", clearTransform );
	gdLens.addCheckbox( "visualize_distortion_model", visualize );

	gdLens.showDialog();
	if ( gdLens.wasCanceled() )
		return false;

	dimension = ( int )gdLens.getNextNumber();
	lambda = ( double )gdLens.getNextNumber();
	firstLayerIndex = gdLens.getNextChoiceIndex();
	lastLayerIndex = gdLens.getNextChoiceIndex();
	clearTransform = gdLens.getNextBoolean();
	visualize = gdLens.getNextBoolean();

	return true;
}