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)):
        
        <dependency>
            <groupId>org.bytedecogroupId>
            <artifactId>javacv-platformartifactId>
            <version>1.4.1version>
        dependency>
        
        <dependency>
            <groupId>org.bytedeco.javacpp-presetsgroupId>
            <artifactId>opencv-platformartifactId>
            <version>3.4.1-1.4.1version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        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实现跨平台视频/图像处理-调用摄像头_第1张图片

 

 

 
 

转载于:https://www.cnblogs.com/songxingzhu/p/9088204.html

你可能感兴趣的:(JAVA中通过JavaCV实现跨平台视频/图像处理-调用摄像头)