视频抽帧Java实现

视频抽帧Java实现

依赖:


        <dependency>
            <groupId>org.bytedecogroupId>
            <artifactId>javacvartifactId>
            <version>1.0version>
        dependency>
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.FrameGrabber.Exception;
import org.bytedeco.javacv.Java2DFrameConverter;

/**
 * 视频抽帧
 *
 */
public class VideoProcessor {

    public static void main(String[] args) throws Exception {
        String filePath = "C:\\Users\\ZHANG\\Desktop\\数据集2\\video";	//批量处理,视频所在文件夹
        String targetPath = "C:\\Users\\ZHANG\\Desktop\\数据集2\\pic\\";	//输出图片文件夹
        File file = new File(filePath);
        if (file.isDirectory()){
            File[] files = file.listFiles();
            for (int i=0; i<files.length; i++) {
                String fpath = files[i].getParent()+"\\"+files[i].getName();
                System.out.println(fpath);
                String fileName = files[i].getName();
                randomGrabberFFmpegImage(fpath, targetPath, fileName.substring(0, fileName.length()-4));
            }
        }
    }


    public static void randomGrabberFFmpegImage(String filePath, String targerFilePath, String targetFileName)
            throws Exception {
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);
        ff.start();
        int ffLength = ff.getLengthInFrames();
        System.out.println(ffLength);
//        double fr = ff.getFrameRate();  //帧率
        System.out.println("帧率: " + ff.getFrameRate());

        System.out.println("视频长度: " + ff.getLengthInTime());
        Frame f;
        int t = 10;		//抽帧间隔
        for (int k=0; k<ffLength; k++){
            f = ff.grabImage();
            if (k%t==0){
                doExecuteFrame(f, targerFilePath, targetFileName, k);
            }
        }
        ff.stop();
    }

    public static void doExecuteFrame(Frame f, String targerFilePath, String targetFileName, int index) {
        if (null == f || null == f.image) {
            return;
        }

        Java2DFrameConverter converter = new Java2DFrameConverter();

        String imageMat = "jpg";
        String FileName = targerFilePath + File.separator + targetFileName + "_" + index + "." + imageMat;
        BufferedImage bi = converter.getBufferedImage(f);
        File output = new File(FileName);
        try {
            ImageIO.write(bi, imageMat, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(其他)