赞
踩
本文介绍如何使用 java 来调用 opencv
opencv下载 页面根据自己电脑操作系统下载最新的安装包,我这里下载的是 4.7.0 版本。
(4.7.0 版本里的 opencv-470.jar 包是使用 jdk11
编译的,所以需要安装 jdk11
后面测试时才不会报错)
下载后运行文件,开始抽取文件
1.idea 的 resource 文件夹下新建个 lib 文件夹。
2.opencv 抽取文件目录下的 opencv\build\java
和 opencv\build\java\x64
这两个目录下,分别把 opencv-470.jar 和 opencv_java470.dll 动态库复制一份到 lib 文件夹下。
3.idea 的 File ——> Project Structure ——> Modules ——> Dependencis ——> 加号 ,把 lib 目录下的 opencv-470.jar 依赖上。
3.测试
package com.hai.tang; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import java.net.URL; import java.util.ArrayList; import java.util.List; import static org.opencv.highgui.HighGui.imshow; import static org.opencv.highgui.HighGui.waitKey; public class MainServer { public static void main(String[] args) throws Exception { //加载opencv的动态库 initOpenCv(); //加载图片并描绘外形 drawAllArea(); } public static String filePath = "F:\\opencv\\aaa.jpeg"; //加载动态库 public static void initOpenCv() { URL url = ClassLoader.getSystemResource("lib/opencv_java470.dll"); System.load(url.getPath()); } public static Mat getImageMat(String path) throws Exception { Mat mat = Imgcodecs.imread(path); if (mat.empty()) { throw new Exception("image is empty"); } else { return mat; } } //在图片上绘制图形外形 private static void drawAllArea() throws Exception { Mat src = getImageMat(filePath); Mat gary = new Mat(); Imgproc.cvtColor(src, gary, Imgproc.COLOR_BGR2GRAY); //图像边缘处理 Mat edges = new Mat(); Imgproc.Canny(gary, edges, 200, 500, 3, false); List<MatOfPoint> list = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); //发现轮廓 Imgproc.findContours(edges, list, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_NONE); //画出轮廓 Imgproc.drawContours(src, list, -1, new Scalar(255, 0, 0), Imgproc.LINE_4, Imgproc.LINE_4); imshow("drawAllArea", src); waitKey(); } }
4.效果
上面代码 initOpenCv 方法里使用了 System.load 去加载 dll 动态链接库,除了使用代码去加载还有其他方式。
比如:
(1) 把 dll 文件路径配置到环境变量;
(2) 把dll文件放到其他系统文件夹或者 jdk/jre 文件夹下;
(3) 把 dll 文件路径加到 JVM参数里;
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。