正确使用Java解锁RTSP摄像头抓帧读流
2020-06-29 本文已影响0人
Balance_1d14
由于大多数情况下,我们的电脑性能是有限的,所以在使用海康摄像头等RTSP抓帧读流的时候,应首先将主码流和辅码流的分辨率降低并且将视频的帧率也降低(这是本人经过无数血的教训实验得出的结论),如下图所示
image.png
读流抓帧是肯定需要开一个专门的线程去读的,在关闭线程的时候通用办法就是开一个while(true或false)的方式来结束一个线程
以下是我的抓帧逻辑(这也是我经过无数个黑夜得出来的几行关键代码):
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class CameraSnatch {
public static void main(String[] args) throws IOException {
//String file = "rtsp://admin:admin123@192.168.18.253/h264/sub/av_stream";
String file = "rtsp://admin:Admin123@192.168.0.105/h264/sub/av_stream";
FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(file);
grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式,不然会丢包很严重
grabber.setImageWidth(1280);
grabber.setImageHeight(720);
System.out.println("grabber start");
grabber.start();
//1.播放视频
CanvasFrame canvasFrame = new CanvasFrame("摄像机");
canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvasFrame.setAlwaysOnTop(true);
OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
while (true){
Frame frame = grabber.grabImage();
opencv_core.Mat mat = converter.convertToMat(frame);
canvasFrame.showImage(frame);
}
//2.帧截图
/* File outPut = new File("E:\\convert\\" + 123 + ".jpeg");
while (true) {
Frame frame = grabber.grabImage();
if (frame != null) {
ImageIO.write(FrameToBufferedImage(frame), "jpeg", outPut);
//grabber.stop();
//grabber.release();
System.out.println("图片已保存");
//break;
}
}*/
}
/**
* 创建BufferedImage对象
*/
public static BufferedImage FrameToBufferedImage(Frame frame) {
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bufferedImage = converter.getBufferedImage(frame);
// bufferedImage=rotateClockwise90(bufferedImage);
return bufferedImage;
}
/**
* 处理图片,将图片旋转90度。
*/
public static BufferedImage rotateClockwise90(BufferedImage bi) {
int width = bi.getWidth();
int height = bi.getHeight();
BufferedImage bufferedImage = new BufferedImage(height, width, bi.getType());
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
bufferedImage.setRGB(j, i, bi.getRGB(i, j));
return bufferedImage;
}
}