opencv3.4图像比较-直方图(java版)

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.opencv.core.*;
import org.opencv.features2d.*;
import org.opencv.imgcodecs.*;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

   /**
	 * 通过直方图比较两张图片
	 * @param _src  原始图
	 * @param _des   目标图
	 * @return
	 */
	private static int compareHist(Mat _src, Mat _des) {
		System.out.println("\n==========直方图比较==========");
		try {

			long startTime = System.currentTimeMillis();
			System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

			Mat mat_src = _src;
			Mat mat_des = _des;

			if (mat_src.empty() || mat_des.empty()) {
				throw new Exception("no file.");
			}

			Mat hsv_src = new Mat();
			Mat hsv_des = new Mat();

			// 转换成HSV
			Imgproc.cvtColor(mat_src, hsv_src, Imgproc.COLOR_BGR2HSV);
			Imgproc.cvtColor(mat_des, hsv_des, Imgproc.COLOR_BGR2HSV);

			List listImg1 = new ArrayList();
			List listImg2 = new ArrayList();
			listImg1.add(hsv_src);
			listImg2.add(hsv_des);

			MatOfFloat ranges = new MatOfFloat(0, 255);
			MatOfInt histSize = new MatOfInt(50);
			MatOfInt channels = new MatOfInt(0);

			Mat histImg1 = new Mat();
			Mat histImg2 = new Mat();

			Imgproc.calcHist(listImg1, channels, new Mat(), histImg1, histSize,
					ranges);
			Imgproc.calcHist(listImg2, channels, new Mat(), histImg2, histSize,
					ranges);

			Core.normalize(histImg1, histImg1, 0, 1, Core.NORM_MINMAX, -1,
					new Mat());
			Core.normalize(histImg2, histImg2, 0, 1, Core.NORM_MINMAX, -1,
					new Mat());

			double result0, result1, result2, result3;
			result0 = Imgproc.compareHist(histImg1, histImg2, 0);
			result1 = Imgproc.compareHist(histImg1, histImg2, 1);
			result2 = Imgproc.compareHist(histImg1, histImg2, 2);
			result3 = Imgproc.compareHist(histImg1, histImg2, 3);

			// 0 - 相关性:度量越高,匹配越准确 “> 0.9”
			// 1 - 卡方: 度量越低,匹配越准确 "< 0.1"
			// 2 - 交叉核: 度量越高,匹配越准确 "> 1.5"
			// 3 - 巴氏距离: 度量越低,匹配越准确 "< 0.3"
			System.out.println("相关性(度量越高,匹配越准确 [基准:0.9]),当前值:" + result0);
			System.out.println("卡方(度量越低,匹配越准确 [基准:0.1]),当前值:" + result1);
			System.out.println("交叉核(度量越高,匹配越准确 [基准:1.5]),当前值:" + result2);
			System.out.println("巴氏距离(度量越低,匹配越准确 [基准:0.3]),当前值:" + result3);

			int count = 0;
			if (result0 > 0.9)
				count++;
			if (result1 < 0.1)
				count++;
			if (result2 > 1.5)
				count++;
			if (result3 < 0.3)
				count++;
			int retVal = 0;
			if (count >= 3) {
				//这是相似的图像
				retVal = 1;
			}

			long estimatedTime = System.currentTimeMillis() - startTime;

			System.out.println("花费时间= " + estimatedTime + "ms");

			return retVal;
		} catch (Exception e) {
			System.out.println("例外:" + e);
		}
		return 0;
	}

你可能感兴趣的:(商业智能)