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;}