OpenCV 是一个开源的计算机视觉库,它提供了许多图像和视频处理的功能。在 Java 中使用 OpenCV 保存视频文件,你需要了解一些基础概念,以及相关的操作步骤。
以下是一个简单的示例代码,演示如何在 Java 中使用 OpenCV 保存视频文件:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.VideoWriter;
public class VideoCaptureExample {
static {
// 加载 OpenCV 本地库
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
// 打开摄像头
VideoCapture camera = new VideoCapture(0);
if (!camera.isOpened()) {
System.out.println("Error: Could not open video device.");
return;
}
// 获取摄像头的分辨率
int width = (int) camera.get(VideoCapture.CAP_PROP_FRAME_WIDTH);
int height = (int) camera.get(VideoCapture.CAP_PROP_FRAME_HEIGHT);
// 创建 VideoWriter 对象
String outputFilePath = "output.mp4";
VideoWriter videoWriter = new VideoWriter(outputFilePath, VideoWriter.fourcc('X', '2', '6', '4'), 30, new Size(width, height));
if (!videoWriter.isOpened()) {
System.out.println("Error: Could not open the output video file for writing.");
return;
}
Mat frame = new Mat();
while (true) {
// 读取一帧
if (!camera.read(frame)) {
System.out.println("Error: Could not read frame.");
break;
}
// 写入帧到视频文件
videoWriter.write(frame);
// 显示帧
HighGui.imshow("Video", frame);
// 按 'q' 键退出循环
if (HighGui.waitKey(1) == 'q') {
break;
}
}
// 释放资源
camera.release();
videoWriter.release();
HighGui.destroyAllWindows();
}
}
OpenCV 支持多种视频编码格式和容器格式。常见的视频编码格式有 H.264、H.265、MPEG-4 等,常见的视频容器格式有 MP4、AVI、MKV 等。
通过以上步骤和方法,你应该能够在 Java 中使用 OpenCV 成功保存视频文件。
领取专属 10元无门槛券
手把手带您无忧上云