Openimaj从集成摄像头或USB摄像头捕获并保存视频到硬盘(java)

时间:2012-07-10 14:13:26

标签: openimaj

我刚从网站安装了几乎所有的openimaj指令库:http://sourceforge.net/p/openimaj/wiki/OpenIMAJ%20From%20Source/库已安装并正常工作。我只需要一个示例代码来从网络摄像头捕获视频并将其保存到硬盘。例如:

这是打开相机并显示视频的代码:


import org.openimaj.image.MBFImage;
import org.openimaj.video.VideoDisplay;
import org.openimaj.video.VideoDisplayListener;
import org.openimaj.video.capture.VideoCapture;

public class VideoDemo {
    ...
    VideoCapture vc = new VideoCapture( 320, 240 );
    VideoDisplay<MBFImage> vd = VideoDisplay.createVideoDisplay( vc );
    ...
}

如何在磁盘上保存[vd]?

1 个答案:

答案 0 :(得分:1)

您需要使用XuggleVideoWriter课程。以下代码在屏幕上显示视频内容,并将内容写入文件,直到按下转义键。视频格式由文件名控制(即“video.flv”创建FLV格式视频)。

package org.openimaj.demos.sandbox;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;

import javax.swing.SwingUtilities;

import org.openimaj.image.MBFImage;
import org.openimaj.video.Video;
import org.openimaj.video.VideoDisplay;
import org.openimaj.video.VideoDisplayListener;
import org.openimaj.video.capture.VideoCapture;
import org.openimaj.video.xuggle.XuggleVideoWriter;

/**
 * Record the webcam to a file.
 * 
 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
 */
public class VideoRecorder extends KeyAdapter implements VideoDisplayListener<MBFImage> {
    private Video<MBFImage> video;
    private VideoDisplay<MBFImage> display;
    private XuggleVideoWriter writer;
    private boolean close = false;

    /**
     * Default constructor
     * @throws IOException
     */
    public VideoRecorder() throws IOException {
        //open webcam
        video = new VideoCapture(320, 240);

        //open display
        display = VideoDisplay.createVideoDisplay(video);

        //open a writer
        writer = new XuggleVideoWriter("video.flv", video.getWidth(), video.getHeight(), 30);

        //set this class to listen to video display events
        display.addVideoListener(this);

        //set this class to listen to keyboard events
        SwingUtilities.getRoot(display.getScreen()).addKeyListener(this);
    }

    @Override
    public void afterUpdate(VideoDisplay<MBFImage> display) {
        //Do nothing
    }

    @Override
    public void beforeUpdate(MBFImage frame) {
        //write a frame 
        if (!close) {
            writer.addFrame(frame);
        }
    }

    @Override
    public void keyPressed(KeyEvent key) {
        //wait for the escape key to be pressed
        close = key.getKeyCode() == KeyEvent.VK_ESCAPE;
    }

    /**
     * Main method
     * @param args ignored
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        new VideoRecorder();
    }
}