JAVA中通过JavaCV实现跨平台视频/图像处理-调用摄像头

一、简介

  JavaCV使用来自计算机视觉领域(OpenCV, FFmpeg, libdc1394, PGR FlyCapture, OpenKinect, librealsense, CL PS3 Eye Driver, videoInput, ARToolKitPlus, flandmark, Leptonica, and Tesseract)领域的研究人员常用库的JavaCPP预设的封装。提供实用程序类,使其功能更易于在Java平台上使用,包括Android。
 
二、案例1:调用摄像头
(1)使用IDEA新建Maven项目,然后在pom.xml中引入下列依赖(因为要用到opencv来实现,所以需要引入opencv-platform包,此包会自动引入各大平台的依赖jar(内含dll)):
        <!-- https://mvnrepository.com/artifact/org.bytedeco/javacv-platform -->
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.4.1</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> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

(2)测试类

import org.bytedeco.javacv.*;
import org.junit.Test; import javax.swing.*;
import java.util.EnumSet; public class JavaCVTest { @Test
public void testCamera() throws InterruptedException, FrameGrabber.Exception {
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start(); //开始获取摄像头数据
CanvasFrame canvas = new CanvasFrame("摄像头");//新建一个窗口
canvas.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
canvas.setAlwaysOnTop(true);
while (true) {
if (!canvas.isDisplayable()) {//窗口是否关闭
grabber.stop();//停止抓取
System.exit(-1);//退出
} Frame frame = grabber.grab(); canvas.showImage(frame);//获取摄像头图像并放到窗口上显示, 这里的Frame frame=grabber.grab(); frame是一帧视频图像
Thread.sleep(50);//50毫秒刷新一次图像
}
} @Test
public void testCamera1() throws FrameGrabber.Exception, InterruptedException {
VideoInputFrameGrabber grabber = VideoInputFrameGrabber.createDefault(0);
grabber.start();
CanvasFrame canvasFrame = new CanvasFrame("摄像头");
canvasFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
canvasFrame.setAlwaysOnTop(true);
while (true) {
if (!canvasFrame.isDisplayable()) {
grabber.stop();
System.exit(-1);
}
Frame frame = grabber.grab();
canvasFrame.showImage(frame);
Thread.sleep(30);
}
}
}

(3)两种方法的测试效果:

JAVA中通过JavaCV实现跨平台视频/图像处理-调用摄像头

 
 
上一篇:Vs2017 typescript 开发小问题


下一篇:Android开发中如何调用摄像头的功能