Example Fit Ellipse

From BoofCV
Revision as of 13:45, 25 December 2013 by Peter (talk | contribs) (Updated for v0.16)
Jump to navigationJump to search

Fitting ellipses to 2D objects found in images is a common task in industrial and scientific settings. In this example, binary blobs are found inside an image of particles and the best fit ellipses found. In a real application the next step could be to analyze the size distribution of the found ellipses to characterize the particles.

Example Code:

Concepts:

  • Object contours/edges
  • Best fit shape

Relevant Applets:

Example Code

/**
 * Demonstration which fits ellipses to object contours in a binary image.
 *
 * @author Peter Abeles
 */
public class ExampleFitEllipse {

	public static void main( String args[] ) {
		// load and convert the image into a usable format
		BufferedImage image = UtilImageIO.loadImage("../data/applet/particles01.jpg");
		ImageFloat32 input = ConvertBufferedImage.convertFromSingle(image, null, ImageFloat32.class);

		ImageUInt8 binary = new ImageUInt8(input.width,input.height);

		// the mean pixel value is often a reasonable threshold when creating a binary image
		double mean = ImageStatistics.mean(input);

		// create a binary image by thresholding
		ThresholdImageOps.threshold(input, binary, (float) mean, true);

		// reduce noise with some filtering
		ImageUInt8 filtered = BinaryImageOps.erode8(binary,null);
		filtered = BinaryImageOps.dilate8(filtered, null);

		// Find the contour around the shapes
		List<Contour> contours = BinaryImageOps.contour(filtered,8,null);

		// Fit an ellipse to each external contour and draw the results
		Graphics2D g2 = image.createGraphics();
		g2.setStroke(new BasicStroke(3));
		g2.setColor(Color.RED);

		for( Contour c : contours ) {
			FitData<EllipseRotated_F64> ellipse = ShapeFittingOps.fitEllipse_I32(c.external,0,false,null);
			VisualizeShapes.drawEllipse(ellipse.shape, g2);
		}

//		ShowImages.showWindow(VisualizeBinaryData.renderBinary(filtered,null),"Binary");
		ShowImages.showWindow(image,"Ellipses");
	}
}