java在Linux平台调用摄像头
一.概述
java调用摄像头的框架有javacv,jmf,webcam等,这三个框架都可用于windows和linux平台,个人更喜欢javacv,因为其功能更强大,github地址 :https://github.com/bytedeco/javacv。
二.示例
1.新建maven项目,并引入依赖包:
<dependencies>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bytedeco.javacpp-presets/opencv-platform -->
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>opencv-platform</artifactId>
<version>3.4.1-1.4.1</version>
</dependency>
</dependencies>
引入maven依赖后会自动加载window_86,window_86_64,Linux_86,Linux_86_84等各个平台的依赖包,所以工程会非常庞大,可手动删除不需要的依赖包。
2.编写测试类:
public static void main(String[] args) throws InterruptedException, IOException {
VideoCapture vc = new opencv_videoio.VideoCapture(0);
CanvasFrame frame = new CanvasFrame("摄像头demo");
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
Mat mat = new Mat();
while(true){
vc.retrieve(mat);
if (vc.grab() && vc.read(mat)) {
frame.showImage(converter.convert(mat));
mat.release();
}
Thread.sleep(30);
}
}
3.设置摄像头参数:
上面是最简单的demo,根据实际需求,可以设置视频的分辨率,翻转(左右,上下),选择等,代码如下:
public static void main(String[] args) throws InterruptedException, IOException {
VideoCapture vc = new opencv_videoio.VideoCapture(0);
vc.set(opencv_videoio.CV_CAP_PROP_FRAME_WIDTH, 2048); //设置分辨率
vc.set(opencv_videoio.CV_CAP_PROP_FRAME_HEIGHT, 1536);
CanvasFrame frame = new CanvasFrame("");
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
Mat mat = new Mat();
ToMat convert= new ToMat();
while(true){
vc.retrieve(mat);
if (vc.grab() && vc.read(mat)) {
Mat result = new Mat();
Mat image = convert.convert(converter.convert(mat));
opencv_core.rotate(image, result, 2); //旋转
opencv_core.flip(image, result, 0); //翻转
frame.showImage(converter.convert(result));
mat.release();
}
Thread.sleep(30);
}