我们在对摄像头(如海康、大华)的视频流实现实时监控的过程中,会涉及到抓图的功能,本文并讲述了使用JavaCV对RTSP视频流进行帧截图的工具类的实现。
- pom.xml进入一下包:
<dependency>
<groupId>net.bramp.ffmpeg</groupId>
<artifactId>ffmpeg</artifactId>
<version>0.6.2</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg-platform</artifactId>
<version>4.0.2-1.4.3</version>
</dependency>
- Java代码工具类实现
package com.video.videoimg;
import javax.swing.JFrame;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.opencv_core.Mat;
import com.missyou.tools.DateHelper;
/***
* RTSP地址的视频流保存帧图片
* @author 懒驴
*
*/
public class RtspVideoSaveImage {
/***
* 1.通过RTSP视频地址截图
* @param rtspUrl RTSP视频流地址
* @param imgUrl 图片保存的地址
* @return 返回成功失败。true false
*/
public static boolean saveScreenshotImg(String rtspUrl, String imgUrl) throws FrameGrabber.Exception {
FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(rtspUrl);
grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式,不然会丢包很严重
grabber.setImageWidth(1920);
grabber.setImageHeight(1080);
grabber.start();
OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
Frame frame = grabber.grabImage();
Mat mat = converter.convertToMat(frame);
// imgUrl ="E:\\data\\img\\" + DateHelper.getSimpDateMillis() + ".png"
return opencv_imgcodecs.imwrite(imgUrl, mat);
}
public static void testzc() throws FrameGrabber.Exception{
String rtsp = "rtsp://admin:jlhl12345@192.168.1.111/h264/ch35/main/av_stream";
FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(rtsp);
grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式,不然会丢包很严重
grabber.setImageWidth(1920);
grabber.setImageHeight(1080);
grabber.start();
//CanvasFrame canvasFrame = new CanvasFrame("RTSP截图");// 创建窗口
//canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置窗口关闭程序是否也跟随关闭
//canvasFrame.setAlwaysOnTop(true);
OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
Frame frame = grabber.grabImage();
//canvasFrame.showImage(frame);
//程序到这里其实已经实现了预览的功能了,下面的方法就是将流保存成图片
//opencv_core.Mat
Mat mat = converter.convertToMat(frame);
opencv_imgcodecs.imwrite("E:\\data\\img\\" + DateHelper.getSimpDateMillis() + ".png", mat);
}
/**测试**/
public static void main(String[] args) {
try {
testzc();
} catch (Exception e) {
System.out.println(e);
}
}
}