How to extract frames from a video java?

12.4k views Asked by At

I'm working on a project to do analysis on a video, and I want to split the video into frames to process individually. I took a look at several open source libraries, including Xuggler and FFMPEG, but they are both outdated and unavailable for use. Is there a simple way that I can extract the frames from the video and process them as a collection of BufferedImage?

3

There are 3 answers

2
Bahramdun Adil On BEST ANSWER

You can use OpenCV Image and Video processing free open source framework. And also has a good Java wrapper.

1
Rohit S On

Follow this code

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("D:/video.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();
        }


    }
}
0
Felipe Oviedo On

Next I leave the code that @Rohit proposed, but updated to 2021

package com.example;
 
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter; 
public class Main { 
    public static void main(String []args) throws IOException, Exception
    {
        File myObj = new File("D:\\x\\x\\x\\x\\video.mp4");
        FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(myObj.getAbsoluteFile());
        frameGrabber.start(); 
        Frame f; 
        try {
            Java2DFrameConverter c = new Java2DFrameConverter(); 
            f = frameGrabber.grab();  
            BufferedImage bi = c.convert(f);
            ImageIO.write(bi,"png", new File("D:\\x\\x\\x\\x\\img.png"));
            frameGrabber.stop();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}