26

我想用java从视频文件(mov)中获取帧样本(jpeg)。是否有捷径可寻。当我在谷歌搜索时,我只能找到从多个 jpg 制作 mov 。我不知道也许我找不到正确的关键字。

4

6 回答 6

68

我知道最初的问题已经解决,但是,我发布这个答案以防其他人像我一样被卡住。

从昨天开始,我已经尝试了一切,我的意思是要做到这一点。所有可用的 Java 库要么已经过时,不再维护,要么缺少任何可用的文档(说真的??!?!)

我尝试了 JFM(旧且无用)、JCodec(没有任何文档)、JJMpeg(看起来很有前途,但由于缺乏 Java 类文档,使用起来非常困难和麻烦)、OpenCV 自动 Java 构建和一些其他库我不记得了。

最后,我决定看看JavaCV的(Github 链接)类,瞧!它包含带有详细文档的 FFMPEG 绑定。

<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv</artifactId>
    <version>1.0</version>
</dependency>

事实证明,有一种非常简单的方法可以将视频帧从视频文件中提取BufferedImage为 JPEG 文件并扩展为 JPEG 文件。FFmpegFrameGrabber 类可以很容易地用于抓取单个帧并将它们转换为BufferedImage. 代码示例如下:

FFmpegFrameGrabber g = new FFmpegFrameGrabber("textures/video/anim.mp4");
g.start();

for (int i = 0 ; i < 50 ; i++) {
    ImageIO.write(g.grab().getBufferedImage(), "png", new File("frame-dump/video-frame-" + System.currentTimeMillis() + ".png"));
}

g.stop();

基本上,这段代码会转储视频的前 50 帧并将它们保存为 PNG 文件。好消息是内部搜索功能适用于实际帧而不是关键帧(我在使用 JCodec 时遇到的问题)

您可以参考 JavaCV 的主页以了解有关可用于从网络摄像头等捕获帧的其他类的更多信息。希望这个答案有所帮助:-)

于 2014-02-28T22:33:56.740 回答
6

Xuggler 完成了这项工作。他们甚至提供了一个完全符合我需要的示例代码。链接在下面

http://xuggle.googlecode.com/svn/trunk/java/xuggle-xuggler/src/com/xuggle/mediatool/demos/DecodeAndCaptureFrames.java

我已经修改了这个链接中的代码,使它只保存视频的第一帧。

import javax.imageio.ImageIO;

import java.io.File;

import java.awt.image.BufferedImage;

import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.MediaListenerAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.Global;

/**
 *  * @author aclarke
 *    @author trebor
 */

public class DecodeAndCaptureFrames extends MediaListenerAdapter
{
  private int mVideoStreamIndex = -1;
  private boolean gotFirst = false;
  private String saveFile;
  private Exception e;
  /** Construct a DecodeAndCaptureFrames which reads and captures
   * frames from a video file.
   * 
   * @param filename the name of the media file to read
   */

  public DecodeAndCaptureFrames(String videoFile, String saveFile)throws Exception
  {
    // create a media reader for processing video
    this.saveFile = saveFile;
    this.e = null;
     IMediaReader reader = ToolFactory.makeReader(videoFile);

    // stipulate that we want BufferedImages created in BGR 24bit color space
    reader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);


    // note that DecodeAndCaptureFrames is derived from
    // MediaReader.ListenerAdapter and thus may be added as a listener
    // to the MediaReader. DecodeAndCaptureFrames implements
    // onVideoPicture().

    reader.addListener(this);

    // read out the contents of the media file, note that nothing else
    // happens here.  action happens in the onVideoPicture() method
    // which is called when complete video pictures are extracted from
    // the media source

      while (reader.readPacket() == null && !gotFirst);

      if (e != null)
          throw e;
  }



  /** 
   * Called after a video frame has been decoded from a media stream.
   * Optionally a BufferedImage version of the frame may be passed
   * if the calling {@link IMediaReader} instance was configured to
   * create BufferedImages.
   * 
   * This method blocks, so return quickly.
   */

  public void onVideoPicture(IVideoPictureEvent event)
  {
    try
    {
      // if the stream index does not match the selected stream index,
      // then have a closer look

      if (event.getStreamIndex() != mVideoStreamIndex)
      {
        // if the selected video stream id is not yet set, go ahead an
        // select this lucky video stream

        if (-1 == mVideoStreamIndex)
          mVideoStreamIndex = event.getStreamIndex();

        // otherwise return, no need to show frames from this video stream

        else
          return;
      }

      ImageIO.write(event.getImage(), "jpg", new File(saveFile));
      gotFirst = true;

    }
    catch (Exception e)
    {
      this.e = e;
    }
  }
}
于 2013-04-01T01:31:37.463 回答
2
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber.Exception;

public class Read{
    public static void main(String []args) throws IOException, Exception
    {
        FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("C:/Users/Digilog/Downloads/Test.mp4");
        frameGrabber.start();
        IplImage i;
        try {

            i = frameGrabber.grab();
            BufferedImage  bi = i.getBufferedImage();
            ImageIO.write(bi,"png", new File("D:/Img.png"));
            frameGrabber.stop();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}
于 2015-03-18T04:20:27.740 回答
2

以下是BoofCV的方法:

String fileName = UtilIO.pathExample("tracking/chipmunk.mjpeg");

MediaManager media = DefaultMediaManager.INSTANCE;

ConfigBackgroundBasic configBasic = new ConfigBackgroundBasic(30, 0.005f);
ImageType imageType = ImageType.single(GrayF32.class);
BackgroundModelMoving background = FactoryBackgroundModel.movingBasic(configBasic, new PointTransformHomography_F32(), imageType);

SimpleImageSequence video = media.openVideo(fileName, background.getImageType());

ImageBase nextFrame;
while(video.hasNext()) {
    nextFrame = video.next();

    // Now do something with it...
}
于 2016-08-14T01:50:37.870 回答
0

也许这会帮助你:

Buffer buf = frameGrabber.grabFrame();
// Convert frame to an buffered image so it can be processed and saved
Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf));
buffImg = new BufferedImage(img.getWidth(this), img.getHeight(this), BufferedImage.TYPE_INT_RGB);
//TODO saving the buffImg

欲了解更多信息:

如何从网络摄像头拍摄单个快照?

于 2013-03-31T23:36:29.480 回答
0

下面显示了从媒体文件请求帧的基本代码。

完整的源代码和视频演示:使用Marvin 框架的
“媒体文件处理”示例..

public class MediaFileExample implements Runnable{

    private MarvinVideoInterface    videoAdapter;
    private MarvinImage             videoFrame;

    public MediaFileExample(){
        try{
            // Create the VideoAdapter used to load the video file
            videoAdapter = new MarvinJavaCVAdapter();
            videoAdapter.loadResource("./res/snooker.wmv");

            // Start the thread for requesting the video frames 
            new Thread(this).start();
        }
        catch(MarvinVideoInterfaceException e){e.printStackTrace();}
    }

    @Override
    public void run() {
        try{
            while(true){
                // Request a video frame
                videoFrame = videoAdapter.getFrame();
            }
        }catch(MarvinVideoInterfaceException e){e.printStackTrace();}
    }

    public static void main(String[] args) {
        MediaFileExample m = new MediaFileExample();
    }
}
于 2014-07-04T11:50:13.510 回答