import java.util.Arrays;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.Range;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
class CompareHist {
public void run(String[] args) {
if (args.length != 3) {
System.err.println("您必须提供 3 个参数,对应于 3 张图像的路径。");
System.exit(0);
}
Mat srcBase = Imgcodecs.imread(args[0]);
Mat srcTest1 = Imgcodecs.imread(args[1]);
Mat srcTest2 = Imgcodecs.imread(args[2]);
如果 (srcBase.empty() || srcTest1.empty() || srcTest2.empty()) {
System.err.println("无法读取图像");
System.exit(0);
}
Mat hsvBase = new Mat(), hsvTest1 = new Mat(), hsvTest2 = new Mat();
Imgproc.cvtColor( srcBase, hsvBase, Imgproc.COLOR_BGR2HSV );
Imgproc.cvtColor( srcTest1, hsvTest1, Imgproc.COLOR_BGR2HSV );
Imgproc.cvtColor( srcTest2, hsvTest2, Imgproc.COLOR_BGR2HSV );
Mat hsvHalfDown = hsvBase.submat( new Range( hsvBase.rows()/2, hsvBase.rows() - 1 ), new Range( 0, hsvBase.cols() - 1 ) );
int hBins = 50, sBins = 60;
int[] histSize = { hBins, sBins };
float[] ranges = { 0, 180, 0, 256 };
int[] channels = { 0, 1 };
Mat histBase = new Mat(), histHalfDown = new Mat(), histTest1 = new Mat(), histTest2 = new Mat();
List<Mat> hsvBaseList = Arrays.asList(hsvBase);
Imgproc.calcHist(hsvBaseList, new MatOfInt(channels), new Mat(), histBase, new MatOfInt(histSize), new MatOfFloat(ranges), false);
Core.normalize(histBase, histBase, 0, 1, Core.NORM_MINMAX);
List<Mat> hsvHalfDownList = Arrays.asList(hsvHalfDown);
Imgproc.calcHist(hsvHalfDownList, new MatOfInt(channels), new Mat(), histHalfDown, new MatOfInt(histSize), new MatOfFloat(ranges), false);
Core.normalize(histHalfDown, histHalfDown, 0, 1, Core.NORM_MINMAX);
List<Mat> hsvTest1List = Arrays.asList(hsvTest1);
Imgproc.calcHist(hsvTest1List, new MatOfInt(channels), new Mat(), histTest1, new MatOfInt(histSize), new MatOfFloat(ranges), false);
Core.normalize(histTest1, histTest1, 0, 1, Core.NORM_MINMAX);
List<Mat> hsvTest2List = Arrays.asList(hsvTest2);
Imgproc.calcHist(hsvTest2List, new MatOfInt(channels), new Mat(), histTest2, new MatOfInt(histSize), new MatOfFloat(ranges), false);
Core.normalize(histTest2, histTest2, 0, 1, Core.NORM_MINMAX);
for( int compareMethod = 0; compareMethod < 4; compareMethod++ ) {
double baseBase = Imgproc.compareHist( histBase, histBase, compareMethod );
double baseHalf = Imgproc.compareHist( histBase, histHalfDown, compareMethod );
double baseTest1 = Imgproc.compareHist( histBase, histTest1, compareMethod );
double baseTest2 = Imgproc.compareHist( histBase, histTest2, compareMethod );
System.out.println("方法 " + compareMethod + " 完美、半基数、基数测试(1)、基数测试(2): " + baseBase + " / " + baseHalf
+ " / " + baseTest1 + " / " + baseTest2);
}
}
}
public class CompareHistDemo {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
new CompareHist().run(args);
}
}