-
代碼都是來自網絡,收集的比較亂,所有找不到出處了。
獲取視頻流的核心代碼
private static void testRtsp() {
//必須要加入這兩個東西
System.load("D:\\opencv-4.1.1\\opencv\\build\\x64\\vc15\\bin\\opencv_world411.dll");
System.load("D:\\opencv-4.1.1\\opencv\\build\\bin\\opencv_videoio_ffmpeg411_64.dll");
VideoCapture vc = new VideoCapture();
boolean isOpen = vc.open("rtsp://admin:[email protected]");
System.out.println("isOpen="+isOpen);
Mat mat = new Mat();
String winName = "showFrame";
int height = 600,width = 800;
HighGui.namedWindow(winName);
HighGui.resizeWindow(winName, width, height);
while(vc.read(mat)){
// 重置大小
Mat dst = new Mat();
Imgproc.resize(mat, dst, new Size(width,height));
// 顯示
HighGui.imshow(winName, dst);
// waitkey 必須要,否則無法顯示
int key = HighGui.waitKey(1);
System.out.println("key="+key);
//esc鍵退出
if(key == 27){
break;
}
//拿到了每幀之後要幹嘛就是後面邏輯的事情了
}
HighGui.destroyAllWindows();
vc.release();
}
效果
- mat的一些處理方式
//mat轉輸入流
public static InputStream mat2InputStream(Mat mat){
MatOfByte mob = new MatOfByte();
imencode(".jpg", mat, mob);
byte[] byteArray = mob.toArray();
return new ByteArrayInputStream(byteArray);
}
//mat轉圖片
public static void mat2File(Mat mat){
MatOfByte mob = new MatOfByte();
imencode(".jpg", mat, mob);
imwrite("f:\\img\\test.png",mat);
// byte[] byteArray = mob.toArray();
}
private static void record(){
System.load("D:\\opencv-4.1.1\\opencv\\build\\x64\\vc15\\bin\\opencv_world411.dll");
System.load("D:\\opencv-4.1.1\\opencv\\build\\bin\\opencv_videoio_ffmpeg411_64.dll");
VideoCapture vc = new VideoCapture();
boolean isOpen = vc.open("rtsp://admin:[email protected]");
System.out.println("isOpen="+isOpen);
Mat mat = new Mat();
VideoWriter vw = new VideoWriter();
Size size = new Size();
size.width = vc.get(CAP_PROP_FRAME_WIDTH);
size.height = vc.get(CAP_PROP_FRAME_HEIGHT);
boolean t = vw.open("f:\\img\\test.avi",VideoWriter.fourcc('M', 'P', '4', '2'),30,size);
System.out.println("開啓狀態:"+t);
int times = 400;//測試錄製時間
while(times-->0 && vc.read(mat)){
vw.write(mat);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
vc.release();
vw.release();
System.out.println("結束");
}
效果