Example Webcam Capture

From BoofCV
Revision as of 04:53, 28 March 2016 by Peter (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Demonstration of how to stream images from Webcam Capture and process them in BoofCV. Webcam Capture is an easy to use library for accessing webcams in Java. In the example below the default webcam is streamed and KLT features are tracked. More examples can be found in the webcam capture examples directory

Example Code:

Concepts:

  • Webcams

Example Code

/**
 * Processes a video feed and tracks points using KLT
 *
 * @author Peter Abeles
 */
public class ExampleTrackingKlt {

	public static void main(String[] args) {

		// tune the tracker for the image size and visual appearance
		ConfigGeneralDetector configDetector = new ConfigGeneralDetector(-1,8,1);
		PkltConfig configKlt = new PkltConfig(3,new int[]{1,2,4,8});

		PointTracker<GrayF32> tracker = FactoryPointTracker.klt(configKlt,configDetector,GrayF32.class,null);

		// Open a webcam at a resolution close to 640x480
		Webcam webcam = UtilWebcamCapture.openDefault(640,480);

		// Create the panel used to display the image and feature tracks
		ImagePanel gui = new ImagePanel();
		gui.setPreferredSize(webcam.getViewSize());

		ShowImages.showWindow(gui,"KLT Tracker",true);

		int minimumTracks = 100;
		while( true ) {
			BufferedImage image = webcam.getImage();
			GrayF32 gray = ConvertBufferedImage.convertFrom(image,(GrayF32)null);

			tracker.process(gray);

			List<PointTrack> tracks = tracker.getActiveTracks(null);

			// Spawn tracks if there are too few
			if( tracks.size() < minimumTracks ) {
				tracker.spawnTracks();
				tracks = tracker.getActiveTracks(null);
				minimumTracks = tracks.size()/2;
			}

			// Draw the tracks
			Graphics2D g2 = image.createGraphics();

			for( PointTrack t : tracks ) {
				VisualizeFeatures.drawPoint(g2,(int)t.x,(int)t.y,Color.RED);
			}

			gui.setBufferedImageSafe(image);
		}
	}
}