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

The following examples show how to use ij.gui.GenericDialog#addChoice() . 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: Interest_Point_Registration.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
protected boolean askForReferenceTile( final GlobalOptimizationSubset subset, final GlobalOptimizationType type, final String title )
{
	final GenericDialog gd = new GenericDialog( title );

	final String[] choice = new String[ subset.getViews().size() ];

	for ( int i = 0; i < choice.length; ++i )
	{
		final ViewSetup vs = type.getSpimData().getSequenceDescription().getViewDescription( subset.getViews().get( i ) ).getViewSetup();
		choice[ i ] = "Angle:" + vs.getAngle().getName() + " Channel:" + vs.getChannel().getName() + " Illum:" + vs.getIllumination().getName() + " Timepoint:" + subset.getViews().get( i ).getTimePointId();
	}

	if ( defaultReferenceTile >= choice.length )
		defaultReferenceTile = 0;

	gd.addChoice( title.replace( " ", "_" ), choice, choice[ defaultReferenceTile ] );
	gd.showDialog();
	
	if ( gd.wasCanceled() )
		return false;

	type.setMapBackReferenceTile( subset, subset.getViews().get( defaultReferenceTile = gd.getNextChoiceIndex() ) );

	return true;
}
 
Example 2
Source File: InteractivePlotter.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
private void setTemplate() {
	if (plot == null)
		return;
	final ArrayList<PlotInstance> plots = getPlots();
	if (plots == null || plots.size() == 0) {
		showMessage("No Plots Available", "No open plots to be used as template!");
		return;
	}
	final GenericDialog gd = new GenericDialog("Apply Template");
	final String[] choices = new String[plots.size()];
	for (int i = 0; i < choices.length; i++)
		choices[i] = plots.get(i).title;
	gd.addChoice("Use_this_plot as template:", choices, null);
	showAsSubDialog(gd);
	if (!gd.wasOKed())
		return;
	plot.useTemplate(plots.get(gd.getNextChoiceIndex()).plot);
	plot.updateImage();
}
 
Example 3
Source File: TransformationModel.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
public boolean queryRegularizedModel()
{
	final GenericDialog gd = new GenericDialog( "Regularization Parameters" );

	gd.addChoice( "Model_to_regularize_with", regularizationModelChoice, regularizationModelChoice[ defaultRegularizationModelIndex ] );
	gd.addNumericField( "Lamba", defaultLambda, 2 );

	gd.showDialog();

	if ( gd.wasCanceled() )
	{
		this.regularize = false;
		return false;
	}

	this.regularizedModelIndex = gd.getNextChoiceIndex();
	this.lambda = gd.getNextNumber();
	this.regularize = true;

	return true;
}
 
Example 4
Source File: DifferenceOf.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Figure out which view to use for the interactive preview
 * 
 * @param dialogHeader
 * @param text
 * @param channel
 * @return
 */
protected ViewId getViewSelection( final String dialogHeader, final String text, final Channel channel )
{
	final ArrayList< ViewDescription > views = SpimData2.getAllViewIdsForChannelSorted( spimData, viewIdsToProcess, channel );
	final String[] viewChoice = new String[ views.size() ];

	for ( int i = 0; i < views.size(); ++i )
	{
		final ViewDescription vd = views.get( i );
		viewChoice[ i ] = "Timepoint " + vd.getTimePointId() + ", Angle " + vd.getViewSetup().getAngle().getName() + ", Illum " + vd.getViewSetup().getIllumination().getName() + ", ViewSetupId " + vd.getViewSetupId();
	}

	if ( defaultViewChoice >= views.size() )
		defaultViewChoice = 0;

	final GenericDialog gd = new GenericDialog( dialogHeader );

	gd.addMessage( text );
	gd.addChoice( "View", viewChoice, viewChoice[ defaultViewChoice ] );
	
	gd.showDialog();
	
	if ( gd.wasCanceled() )
		return null;

	final ViewId viewId = views.get( defaultViewChoice = gd.getNextChoiceIndex() );

	return viewId;
}
 
Example 5
Source File: SkewImagesPopup.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()) );
	GenericDialog gd = new GenericDialog( "(De)Skew Parameters" );
	
	gd.addChoice( "Skew Direction", axesChoice, axesChoice[0] );
	gd.addChoice( "Skew Along Which Axis", axesChoice, axesChoice[2] );
	gd.addSlider( "Angle", -90, 90, 45 );

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

	final int direction = gd.getNextChoiceIndex();
	final int skewAxis = gd.getNextChoiceIndex();
	final double angle = gd.getNextNumber() / 180 * Math.PI;

	SkewImages.applySkewToData( spimData.getViewRegistrations(), dims, views, direction, skewAxis, angle );

	panel.updateContent();
	panel.bdvPopup().updateBDV();
}
 
Example 6
Source File: RGLDM.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addQuery( final GenericDialog gd, final RegistrationType registrationType )
{
	gd.addChoice( "Transformation model", TransformationModel.modelChoice, TransformationModel.modelChoice[ defaultModel ] );
	gd.addCheckbox( "Regularize_model", defaultRegularize );
	gd.addSlider( "Number_of_neighbors for the descriptors", 3, 10, RGLDMParameters.numNeighbors );
	gd.addSlider( "Redundancy for descriptor matching", 0, 10, RGLDMParameters.redundancy );		
	gd.addSlider( "Significance required for a descriptor match", 1.0, 10.0, RGLDMParameters.ratioOfDistance );
	gd.addSlider( "Allowed_error_for_RANSAC (px)", 0.5, 20.0, RANSACParameters.max_epsilon );
}
 
Example 7
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 8
Source File: Treeline.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
protected boolean askAdjustRadius(final Node<Float> nd) {

		final GenericDialog gd = new GenericDialog("Adjust radius");
		final Calibration cal = layer_set.getCalibration();
		String unit = cal.getUnit();
		if (!unit.toLowerCase().startsWith("pixel")) {
			final String[] units = new String[]{"pixels", unit};
			gd.addChoice("Units:", units, units[1]);
			gd.addNumericField("Radius:", nd.getData() * cal.pixelWidth, 2);
			final TextField tfr = (TextField) gd.getNumericFields().get(0);
			((Choice)gd.getChoices().get(0)).addItemListener(new ItemListener() {
				@Override
                public void itemStateChanged(final ItemEvent ie) {
					final double val = Double.parseDouble(tfr.getText());
					if (Double.isNaN(val)) return;
					tfr.setText(Double.toString(units[0] == ie.getItem() ?
									val / cal.pixelWidth
								      : val * cal.pixelWidth));
				}
			});
		} else {
			unit = null;
			gd.addNumericField("Radius:", nd.getData(), 2, 10, "pixels");
		}
		final String[] choices = {"this node only", "nodes until next branch or end node", "entire subtree"};
		gd.addChoice("Apply to:", choices, choices[0]);
		gd.showDialog();
		if (gd.wasCanceled()) return false;
		double radius = gd.getNextNumber();
		if (Double.isNaN(radius) || radius < 0) {
			Utils.log("Invalid radius: " + radius);
			return false;
		}
		if (null != unit && 1 == gd.getNextChoiceIndex() && 0 != radius) {
			// convert radius from units to pixels
			radius = radius / cal.pixelWidth;
		}
		final float r = (float)radius;
		final Node.Operation<Float> op = new Node.Operation<Float>() {
			@Override
			public void apply(final Node<Float> node) throws Exception {
				node.setData(r);
			}
		};
		// Apply to:
		try {
			layer_set.addDataEditStep(this);
			switch (gd.getNextChoiceIndex()) {
				case 0:
					// Just the node
					nd.setData(r);
					break;
				case 1:
					// All the way to the next branch or end point
					nd.applyToSlab(op);
					break;
				case 2:
					// To the entire subtree of nodes
					nd.applyToSubtree(op);
					break;
				default:
					return false;
			}
			layer_set.addDataEditStep(this);
		} catch (final Exception e) {
			IJError.print(e);
			layer_set.undoOneStep();
		}

		calculateBoundingBox(layer);
		Display.repaint(layer_set);

		return true;
	}
 
Example 9
Source File: ExtendedMinAndMax3DPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
	public void run(String arg) {
		
		if ( IJ.getVersion().compareTo("1.48a") < 0 )
		{
			IJ.error( "Regional Minima and Maxima", "ERROR: detected ImageJ version " + IJ.getVersion()  
					+ ".\nThis plugin requires version 1.48a or superior, please update ImageJ!" );
			return;
		}
		
		ImagePlus imagePlus = IJ.getImage();
		
		if (imagePlus.getStackSize() == 1) {
			IJ.error("Requires a Stack");
			return;
		}
		
		ImageStack stack = imagePlus.getStack();
		int sizeX = stack.getWidth();
		int sizeY = stack.getHeight();
		int sizeZ = stack.getSize();
		boolean isGray8 = stack.getBitDepth() == 8;
		double minValue, maxValue;
		if (isGray8) {
			minValue = 1;
			maxValue = 255;
		} else {
			minValue = Double.MAX_VALUE;
			maxValue = Double.MIN_VALUE;
			for (int z = 0; z < sizeZ; z++) {
				for (int y = 0; y < sizeY; y++) {
					for (int x = 0; x < sizeX; x++) {
						double val = stack.getVoxel(x, y, z);
						minValue = Math.min(minValue, val);
						maxValue = Math.max(maxValue, val);
					}
				}
			}
		}
		
		// Create the configuration dialog
		GenericDialog gd = new GenericDialog("Extended Min & Max 3D");
		gd.addChoice("Operation", Operation.getAllLabels(), 
				Operation.EXTENDED_MINIMA.label);
		gd.addSlider("Dynamic", minValue, maxValue, 10);		
		gd.addChoice("Connectivity", connectivityLabels, connectivityLabels[0]);
//		gd.addHelp("http://imagejdocu.tudor.lu/doku.php?id=plugin:morphology:fast_morphological_filters:start");
        gd.showDialog();
        if (gd.wasCanceled())
        	return;
        
		long t0 = System.currentTimeMillis();
		
		// extract chosen parameters
		Operation op = Operation.fromLabel(gd.getNextChoice());
		int dynamic = (int) gd.getNextNumber();
		int conn = connectivityValues[gd.getNextChoiceIndex()];
        
		ImageStack result = op.apply(stack, dynamic, conn);
		
		String newName = createResultImageName(imagePlus, op);
		ImagePlus resultPlus = new ImagePlus(newName, result);
		resultPlus.copyScale(imagePlus);
				
		resultPlus.show();
		
		resultPlus.setSlice(imagePlus.getCurrentSlice());

		long t1 = System.currentTimeMillis();
		IJUtils.showElapsedTime(op.toString(), t1 - t0, imagePlus);
	}
 
Example 10
Source File: BoundingBoxGUI.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Query the necessary parameters for the bounding box
 * 
 * @param fusion - the fusion for which the bounding box is computed, can be null
 * @param imgExport - the export module used, can be null
 * @return
 */
public boolean queryParameters( final Fusion fusion, final ImgExport imgExport, final boolean allowModifyDimensions )
{
	final boolean compress = fusion == null ? false : fusion.compressBoundingBoxDialog();
	final boolean supportsDownsampling = fusion == null ? false : fusion.supportsDownsampling();
	final boolean supports16BitUnsigned = fusion == null ? false : fusion.supports16BitUnsigned();

	final GenericDialog gd = getSimpleDialog( compress, allowModifyDimensions );

	if ( !compress )
		gd.addMessage( "" );

	if ( supportsDownsampling )
		gd.addSlider( "Downsample fused dataset", 1.0, 10.0, BoundingBoxGUI.staticDownsampling );
	
	if ( supports16BitUnsigned )
		gd.addChoice( "Pixel_type", pixelTypes, pixelTypes[ defaultPixelType ] );

	if ( fusion != null && imgExport != null )
		gd.addChoice( "ImgLib2_container", imgTypes, imgTypes[ defaultImgType ] );

	if ( fusion != null )
		fusion.queryAdditionalParameters( gd );

	if ( imgExport != null )
		imgExport.queryAdditionalParameters( gd, spimData );

	gd.addMessage( "Estimated size: ", GUIHelper.largestatusfont, GUIHelper.good );
	Label l1 = (Label)gd.getMessage();
	gd.addMessage( "???x???x??? pixels", GUIHelper.smallStatusFont, GUIHelper.good );
	Label l2 = (Label)gd.getMessage();

	final ManageListeners m = new ManageListeners( gd, gd.getNumericFields(), gd.getChoices(), l1, l2, fusion, imgExport, supportsDownsampling, supports16BitUnsigned );

	if ( fusion != null )
		fusion.registerAdditionalListeners( m );

	m.update();

	gd.showDialog();

	if ( gd.wasCanceled() )
		return false;

	if ( allowModifyDimensions )
	{
		this.min[ 0 ] = (int)Math.round( gd.getNextNumber() );
		this.min[ 1 ] = (int)Math.round( gd.getNextNumber() );
		this.min[ 2 ] = (int)Math.round( gd.getNextNumber() );

		this.max[ 0 ] = (int)Math.round( gd.getNextNumber() );
		this.max[ 1 ] = (int)Math.round( gd.getNextNumber() );
		this.max[ 2 ] = (int)Math.round( gd.getNextNumber() );
	}
	else
	{
		setNFIndex( gd, 6 );
	}

	if ( supportsDownsampling )
		this.downsampling = BoundingBoxGUI.staticDownsampling = (int)Math.round( gd.getNextNumber() );
	else
		this.downsampling = 1;

	if ( supports16BitUnsigned )
		this.pixelType = BoundingBoxGUI.defaultPixelType = gd.getNextChoiceIndex();
	else
		this.pixelType = BoundingBoxGUI.defaultPixelType = 0; //32-bit

	if ( fusion != null && imgExport != null )
		this.imgtype = BoundingBoxGUI.defaultImgType = gd.getNextChoiceIndex();

	if ( min[ 0 ] > max[ 0 ] || min[ 1 ] > max[ 1 ] || min[ 2 ] > max[ 2 ] )
	{
		IOFunctions.println( "Invalid coordinates, min cannot be larger than max" );
		return false;
	}

	if ( fusion != null )
		if ( !fusion.parseAdditionalParameters( gd ) )
			return false;

	if ( imgExport != null )
		if ( !imgExport.parseAdditionalParameters( gd, spimData ) )
			return false;

	BoundingBoxGUI.defaultMin[ 0 ] = min[ 0 ];
	BoundingBoxGUI.defaultMin[ 1 ] = min[ 1 ];
	BoundingBoxGUI.defaultMin[ 2 ] = min[ 2 ];
	BoundingBoxGUI.defaultMax[ 0 ] = max[ 0 ];
	BoundingBoxGUI.defaultMax[ 1 ] = max[ 1 ];
	BoundingBoxGUI.defaultMax[ 2 ] = max[ 2 ];

	return true;
}
 
Example 11
Source File: AnalyzeRegions3D.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("Analyze Regions 3D");
      gd.addCheckbox("Volume", true);
      gd.addCheckbox("Surface_Area", true);
      gd.addCheckbox("Mean_Breadth", true);
      gd.addCheckbox("Sphericity", true);
      gd.addCheckbox("Euler_Number", true);
      gd.addCheckbox("Bounding_Box", true);
      gd.addCheckbox("Centroid", true);
      gd.addCheckbox("Equivalent_Ellipsoid", true);
      gd.addCheckbox("Ellipsoid_Elongations", 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();
      computeMeanBreadth 	= gd.getNextBoolean();
      computeSphericity 	= gd.getNextBoolean();
      computeEulerNumber	= gd.getNextBoolean();
      computeBoundingBox  = gd.getNextBoolean();
      computeCentroid     = gd.getNextBoolean();
      computeEllipsoid    = gd.getNextBoolean();
      computeElongations 	= gd.getNextBoolean();
      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 12
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 13
Source File: DifferenceOfGaussian.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void addAddtionalParameters( final GenericDialog gd )
{
	gd.addChoice( "Compute_on", computationOnChoice, computationOnChoice[ defaultComputationChoiceIndex ] );
	
}
 
Example 14
Source File: GeodesicDiameter3DPlugin.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("Geodesic Diameter 3D");
	gd.addChoice("Label Image (3D):", imageNames, selectedImageName);
	// Set Chessknight weights as default
	gd.addChoice("Distances", ChamferWeights3D.getAllLabels(), 
			ChamferWeights3D.WEIGHTS_3_4_5_7.toString());
	gd.showDialog();
	
	if (gd.wasCanceled())
		return;
	
	// set up current parameters
	int labelImageIndex = gd.getNextChoiceIndex();
	ImagePlus labelPlus = WindowManager.getImage(labelImageIndex+1);
	ChamferWeights3D weights = ChamferWeights3D.fromLabel(gd.getNextChoice());
	
	// check if image is a label image
	if (!LabelImages.isLabelImageType(labelPlus))
	{
		IJ.showMessage("Input image should be a label image");
		return;
	}
	
	// extract label ImageProcessor
	ImageStack labelImage = labelPlus.getStack();
	
	// Compute geodesic diameters, using floating-point calculations
	long start = System.nanoTime();
	ResultsTable table = process(labelImage, weights.getFloatWeights());
	long finalTime = System.nanoTime();
	
	// Final time, displayed in milliseconds
	float elapsedTime = (finalTime - start) / 1000000.0f;

	// display the result table
	String tableName = labelPlus.getShortTitle() + "-GeodDiameters"; 
	table.show(tableName);

	IJUtils.showElapsedTime("Geodesic Diameter 3D", (long) elapsedTime, labelPlus);
	
	
	// extract column corresponding to geodesic diameter
	int gdIndex = table.getColumnIndex("Geod. Diam.");
	double[] geodDiamArray = table.getColumnAsDoubles(gdIndex);
	
	// Check validity of resulting geodesic diameters
	for (double geodDiam : geodDiamArray)
	{
		if (Float.isInfinite((float) geodDiam))
		{
			IJ.showMessage("Geodesic Diameter Warning", "Some geodesic diameters are infinite,\n"
					+ "meaning that some particles are not connected.\n" + "Maybe labeling was not performed?");
			break;
		}
	}
}
 
Example 15
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 16
Source File: CenterOfMass.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addQuery( final GenericDialog gd, final RegistrationType registrationType )
{
	gd.addChoice( "Type of Center Computation", centerChoice, centerChoice[ defaultCenterChoice ] );
}
 
Example 17
Source File: MorphologicalReconstruction3DPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void run(String arg) {
	// Open a dialog to choose:
	// - mask image
	// - marker image
	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("Morphological Reconstruction 3D");
	
	gd.addChoice("Marker Image", imageNames, IJ.getImage().getTitle());
	gd.addChoice("Mask Image", imageNames, IJ.getImage().getTitle());
	gd.addChoice("Type of Reconstruction", 
			Operation.getAllLabels(), 
			Operation.BY_DILATION.label);
	gd.addChoice("Connectivity", 
			Conn3D.getAllLabels(), 
			Conn3D.C6.label);
	gd.showDialog();
	
	if (gd.wasCanceled())
		return;

	// set up current parameters
	int markerImageIndex = gd.getNextChoiceIndex();
	ImagePlus markerPlus = WindowManager.getImage(markerImageIndex + 1);
	int maskImageIndex = gd.getNextChoiceIndex();
	ImagePlus maskPlus = WindowManager.getImage(maskImageIndex + 1);
	Operation op = Operation.fromLabel(gd.getNextChoice());
	int conn = Conn3D.fromLabel(gd.getNextChoice()).getValue();

	// Extract image procesors
	ImageStack marker = markerPlus.getStack();
	ImageStack mask = maskPlus.getStack();
	if (!Images3D.isSameSize(marker, mask))
	{
		IJ.error("Image Size Error", "Both marker and mask images must have same size");
	}
	
	long t0 = System.currentTimeMillis();
	
	// Compute geodesic reconstruction
	ImageStack result = op.applyTo(marker, mask, conn);
	
	// Keep same color model
	result.setColorModel(mask.getColorModel());

	// create resulting image
	String newName = maskPlus.getShortTitle() + "-geodRec";
	ImagePlus resultPlus = new ImagePlus(newName, result);
	resultPlus.copyScale(maskPlus);
	resultPlus.show();
	
	resultPlus.setSlice(maskPlus.getCurrentSlice());

	long t1 = System.currentTimeMillis();
	IJUtils.showElapsedTime(op.toString(), t1 - t0, markerPlus);
}
 
Example 18
Source File: Interactive_Remove_Detections.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run( final String arg0 )
{
	// ask for everything but the channels
	final LoadParseQueryXML result = new LoadParseQueryXML();

	if ( !result.queryXML( "Interactively remove detections", false, false, false, false ) )
		return;

	final GenericDialog gd = new GenericDialog( "Select View" );

	final List< TimePoint > timepoints = result.getTimePointsToProcess();
	final String[] timepointNames = new String[ timepoints.size() ];
	for ( int i = 0; i < timepointNames.length; ++i )
		timepointNames[ i ] = result.getTimePointsToProcess().get( i ).getName();
	
	final List< Angle > angles = result.getData().getSequenceDescription().getAllAnglesOrdered();
	final String[] angleNames = new String[ angles.size() ];
	for ( int i = 0; i < angles.size(); ++i )
		angleNames[ i ] = angles.get( i ).getName();

	final List< Channel > channels = result.getData().getSequenceDescription().getAllChannelsOrdered();
	final String[] channelNames = new String[ channels.size() ];
	for ( int i = 0; i < channels.size(); ++i )
		channelNames[ i ] = channels.get( i ).getName();

	final List< Illumination > illuminations = result.getData().getSequenceDescription().getAllIlluminationsOrdered();
	final String[] illuminationNames = new String[ illuminations.size() ];
	for ( int i = 0; i < illuminations.size(); ++i )
		illuminationNames[ i ] = illuminations.get( i ).getName();

	gd.addChoice( "Angle", angleNames, angleNames[ defaultAngleChoice ] );
	gd.addChoice( "Channel", channelNames, channelNames[ defaultChannelChoice ] );
	gd.addChoice( "Illumination", illuminationNames, illuminationNames[ defaultIlluminationChoice ] );
	gd.addChoice( "Timepoint", timepointNames, timepointNames[ defaultTimepointChoice ] );
	gd.addMessage( "" );
	gd.addChoice( "Projection", projectionChoice, projectionChoice[ defaultProjectionChoice ] );

	gd.showDialog();

	if ( gd.wasCanceled() )
		return;

	final Angle angle = angles.get( defaultAngleChoice = gd.getNextChoiceIndex() );
	final Channel channel = channels.get( defaultChannelChoice = gd.getNextChoiceIndex() );
	final Illumination illumination = illuminations.get( defaultIlluminationChoice = gd.getNextChoiceIndex() );
	final TimePoint tp = timepoints.get( defaultTimepointChoice = gd.getNextChoiceIndex() );

	final int projection = defaultProjectionChoice = gd.getNextChoiceIndex();

	// get the corresponding viewid
	final ViewId viewId = SpimData2.getViewId( result.getData().getSequenceDescription(), tp, channel, angle, illumination );
	final String name = "angle: " + angle.getName() + " channel: " + channel.getName() + " illum: " + illumination.getName() + " timepoint: " + tp.getName();

	// this happens only if a viewsetup is not present in any timepoint
	// (e.g. after appending fusion to a dataset)
	if ( viewId == null )
	{
		IOFunctions.println( "This ViewSetup is not present for this timepoint: angle: " + name );
		return;
	}
	
	// get the viewdescription
	final ViewDescription viewDescription = result.getData().getSequenceDescription().getViewDescription( 
			viewId.getTimePointId(), viewId.getViewSetupId() );

	// check if this viewid is present in the current timepoint
	if ( !viewDescription.isPresent() )
	{
		IOFunctions.println( "This ViewSetup is not present for this timepoint: angle: " + name );
		return;
	}

	// XY == along z(2)
	// XZ == along y(1)
	// yz == along x(0)
	final int projectionDim = 2 - projection;

	final Pair< String, String > labels = queryLabelAndNewLabel( result.getData(), viewDescription );

	if ( labels == null )
		return;

	if ( !removeDetections( result.getData(), viewDescription, projectionDim, labels.getA(), labels.getB() ) )
		return;

	// now save it
	SpimData2.saveXML( result.getData(), result.getXMLFileName(), result.getClusterExtension() );
}
 
Example 19
Source File: MaxFeretDiameterPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void run(String arg)
{
	// Open a dialog to choose:
	// - a label image
	// - image to display results
	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. Feret Diameter");
	gd.addChoice("Label Image:", imageNames, selectedImageName);
	// Set Chessknight weights as default
	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 labelPlus = WindowManager.getImage(labelImageIndex+1);
       boolean overlay = gd.getNextBoolean();
	int resultImageIndex = gd.getNextChoiceIndex();
	
	// check if image is a label image
	if (!LabelImages.isLabelImageType(labelPlus))
	{
		IJ.showMessage("Input image should be a label image");
		return;
	}
	
	// Compute max Feret diameters
	MaxFeretDiameter op = new MaxFeretDiameter();
	Map<Integer, PointPair2D> maxDiamsMap = op.analyzeRegions(labelPlus);
	
	// Display the result Table
       ResultsTable results = op.createTable(maxDiamsMap);

       // create string for indexing results
	String tableName = labelPlus.getShortTitle() + "-FeretDiams"; 
   
	// show result
	results.show(tableName);

	// Optionally display overlay
	if (overlay)
	{
		ImagePlus resultImage = WindowManager.getImage(resultImageIndex + 1);
		drawDiameters(resultImage, maxDiamsMap);
	}
   }
 
Example 20
Source File: Distortion_Correction.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Setup as a three step dialog.
 */
@Override
public boolean setup( final String title )
{
	source_dir = "";
	while ( source_dir == "" )
	{
		final DirectoryChooser dc = new DirectoryChooser( "Calibration Images" );
		source_dir = dc.getDirectory();
		if ( null == source_dir ) return false;

		source_dir = source_dir.replace( '\\', '/' );
		if ( !source_dir.endsWith( "/" ) ) source_dir += "/";
	}

	final String exts = ".tif.jpg.png.gif.tiff.jpeg.bmp.pgm";
	names = new File( source_dir ).list(
			new FilenameFilter()
			{
				@Override
                      public boolean accept( final File dir, final String name )
				{
					final int idot = name.lastIndexOf( '.' );
					if ( -1 == idot ) return false;
					return exts.contains( name.substring( idot ).toLowerCase() );
				}
			} );
	Arrays.sort( names );

	final GenericDialog gd = new GenericDialog( title );

	gd.addNumericField( "number_of_images :", 9, 0 );
	gd.addChoice( "first_image :", names, names[ 0 ] );
	gd.addNumericField( "power_of_polynomial_kernel :", dimension, 0 );
	gd.addNumericField( "lambda :", lambda, 6 );
	gd.addCheckbox( "apply_correction_to_images", applyCorrection );
	gd.addCheckbox( "visualize results", visualizeResults );
	final String[] options = new String[]{ "save", "load" };
	gd.addChoice( "What to do? ", options, options[ saveOrLoad ] );
	gd.addStringField( "file_name: ", saveFileName );
	gd.showDialog();

	if (gd.wasCanceled()) return false;

	numberOfImages = ( int )gd.getNextNumber();
	firstImageIndex = gd.getNextChoiceIndex();
	dimension = ( int )gd.getNextNumber();
	lambda = gd.getNextNumber();
	applyCorrection = gd.getNextBoolean();
	visualizeResults = gd.getNextBoolean();
	saveOrLoad = gd.getNextChoiceIndex();
	saveFileName = gd.getNextString();

	if ( saveOrLoad == 0 || visualizeResults )
	{
		final GenericDialog gds = new GenericDialog( title );
		SIFT.addFields( gds, sift );

		gds.addNumericField( "closest/next_closest_ratio :", rod, 2 );

		gds.addMessage( "Geometric Consensus Filter:" );
		gds.addNumericField( "maximal_alignment_error :", maxEpsilon, 2, 6, "px" );
		gds.addNumericField( "inlier_ratio :", minInlierRatio, 2 );
		gds.addChoice( "expected_transformation :", modelStrings, modelStrings[ expectedModelIndex ] );

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

		SIFT.readFields( gds, sift );

		rod = ( float )gds.getNextNumber();

		maxEpsilon = ( float )gds.getNextNumber();
		minInlierRatio = ( float )gds.getNextNumber();
		expectedModelIndex = gds.getNextChoiceIndex();

		return !( gd.invalidNumber() || gds.invalidNumber() );
	}

	return !gd.invalidNumber();
}