1.访问opencv官网,下载源代码。
opencv
2.选择相应版本的源码下载
我这里用的是4.8.1版本的源码进行安装,opencv-4.8.1.tar.gz
安装命令
tar xvf opencv-4.8.1.tar.gz
#在当前文件夹创建build文件,并进入
mkdir build && cd build
#执行编译命令,如果没有cmake请自行安装
cmake ../opencv-4.8.1
#再执行安装命令
sudo make install
#安装成功后验证,执行命令
opencv_version
显示:4.8.1
3.java使用opencv
在编译目录:build/bin下可以找到opencv-481.jar
在编译目录:build/lib下可以找到libopencv_java481.so的动态库,将动态库放入/usr/lib64目录下,当然,你也可以放到指定目录进行加载
// 加载OpenCV库
static {System.loadLibrary("opencv_java481");
}// 比较两张图片并生成标记不同点的新图片public static List<Map<String, Integer>> compareImages(String img1Url, String img2Url, String resultPath) throws IOException {// 读取图片Mat img1 = readImage(img1Url);Mat img2 = readImage(img2Url);List<Map<String, Integer>> diffs = new ArrayList<>();// 调整图片大小为相同尺寸if (!img1.size().equals(img2.size())) {int height = (int) Math.min(img1.height(), img2.height());int width = (int) Math.min(img1.width(), img2.width());Size size = new Size(width, height);Imgproc.resize(img1, img1, size);Imgproc.resize(img2, img2, size);}// 转换为灰度图Mat gray1 = new Mat();Mat gray2 = new Mat();Imgproc.cvtColor(img1, gray1, Imgproc.COLOR_BGR2GRAY);Imgproc.cvtColor(img2, gray2, Imgproc.COLOR_BGR2GRAY);// 计算差异Mat diff = new Mat();Core.absdiff(gray1, gray2, diff);// 二值化处理Mat thresh = new Mat();Imgproc.threshold(diff, thresh, 30, 255, Imgproc.THRESH_BINARY);// 形态学操作,消除噪点Mat kernel = Mat.ones(5, 5, CvType.CV_8U);Imgproc.morphologyEx(thresh, thresh, Imgproc.MORPH_OPEN, kernel);Imgproc.morphologyEx(thresh, thresh, Imgproc.MORPH_CLOSE, kernel);// 查找轮廓List<MatOfPoint> contours = new ArrayList<>();Mat hierarchy = new Mat();Imgproc.findContours(thresh, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);// 在原图上标记不同区域Mat resultImg = img1.clone();for (MatOfPoint contour : contours) {// 计算轮廓的边界框Rect rect = Imgproc.boundingRect(contour);int x = rect.x;int y = rect.y;int w = rect.width;int h = rect.height;// 过滤小的差异区域if (w * h > 3000) { // 只显示面积大于3000像素的差异Map<String, Integer> diffMap = new HashMap<>();diffMap.put("x", x);diffMap.put("y", y);diffMap.put("w", w);diffMap.put("h", h);diffs.add(diffMap);Imgproc.rectangle(resultImg, new Point(x, y), new Point(x + w, y + h), new Scalar(0, 0, 255), 2);}}// 保存结果图片Imgcodecs.imwrite(resultPath, resultImg);// 返回不同区域return diffs;}