Page 195 - The Definitive Guide to Building Java Robots
P. 195
Preston_5564C06.fm Page 176 Friday, September 23, 2005 5:13 AM
176 CHAPTER 6 ■ VISION
The heart of vision processing is the capture of a single frame of a video stream into an
image that can be processed. In the next example, we’ll do just that: capture a single frame and
then display it in the ImageViewer class created in the previous section.
Code Objective
The objective here is to capture a single frame from the web camera and display it as an image
in ImageViewer.
Code Discussion
The GetFrame class has a single field, player—this is the javax.media.Player interface. See
Example 6-7. The constructor takes a String that will be used to create a “realized” player via
the Media Locator class sampled in the FindCamera class. To be “realized” means that the
player is in the “realized” state, meaning it knows what resources it needs and has the necessary
information regarding the type of media it is to present. Once the player is created, I have to
start it. I then pause two and a half seconds for the camera to finish initializing.
The next method is getAwtImage(). I’ll use the FrameGrabbingControl from the Java
Media Framework to convert the frame to a buffer. Next, I convert the buffer to a java.awt.Image.
I’ll also create a similar method to get a BufferedImage that just calls the getAwtImage().
The final method of the class is close(). This closes and deallocates the player.
In the sample program in main(), I create the GetFrame object via the URL “vfw://0”. This
URL again can be obtained by running the JMF Registry Editor. Next, I call the getBufferedImage
method and put this image in a BufferedImage. The BufferedImage is then used to construct
the ImageViewer. Figure 6-7 shows the sample output of this class.
Example 6-7. GetFrame.java
package com.scottpreston.javarobot.chapter6;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.media.Buffer;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
public class GetFrame {
private Player player;
public GetFrame(String url) throws Exception{