导入 java.util.ArrayList;
导入 java.util.List;
导入 org.opencv.core.Core;
导入 org.opencv.core.CvType;
导入 org.opencv.core.Mat;
导入 org.opencv.core.MatOfFloat;
导入 org.opencv.core.MatOfInt;
导入 org.opencv.core.Point;
导入 org.opencv.core.Scalar;
导入 org.opencv.highgui.HighGui;
导入 org.opencv.imgcodecs.Imgcodecs;
导入 org.opencv.imgproc.Imgproc;
类 CalcHist {
公共 void run(String[] args) {
String filename = args.length > 0 ? args[0] : "../data/lena.jpg";
Mat src = Imgcodecs.imread(filename);
如果 (src.empty()) {
System.err.println("无法读取图像:" + filename);
System.exit(0);
}
List<Mat> bgrPlanes = new ArrayList<>();
Core.split(src, bgrPlanes);
int histSize = 256;
float[] range = {0, 256};
MatOfFloat histRange = new MatOfFloat(range);
boolean accumulate = false;
Mat bHist = new Mat(), gHist = new Mat(), rHist = new Mat();
Imgproc.calcHist(bgrPlanes, new MatOfInt(0), new Mat(), bHist, new MatOfInt(histSize), histRange, accumulate);
Imgproc.calcHist(bgrPlanes, new MatOfInt(1), new Mat(), gHist, new MatOfInt(histSize), histRange, accumulate);
Imgproc.calcHist(bgrPlanes, new MatOfInt(2), new Mat(), rHist, new MatOfInt(histSize), histRange, accumulate);
int histW = 512, histH = 400;
int binW = (int) Math.round((double) histW / histSize);
Mat histImage = new Mat( histH, histW, CvType.CV_8UC3, new Scalar( 0,0,0) );
Core.normalize(bHist, bHist, 0, histImage.rows(), Core.NORM_MINMAX);
Core.normalize(gHist, gHist, 0, histImage.rows(), Core.NORM_MINMAX);
Core.normalize(rHist, rHist, 0, histImage.rows(), Core.NORM_MINMAX);
float[] bHistData = new float[(int) (bHist.total() * bHist.channels())];
bHist.get(0, 0, bHistData);
float[] gHistData = new float[(int) (gHist.total() * gHist.channels())];
gHist.get(0, 0, gHistData);
float[] rHistData = new float[(int) (rHist.total() * rHist.channels())];
rHist.get(0, 0, rHistData);
for( int i = 1; i < histSize; i++ ) {
Imgproc.line(histImage, new Point(binW * (i - 1), histH - Math.round(bHistData[i - 1])),
new Point(binW * (i), histH - Math.round(bHistData[i])), new Scalar(255, 0, 0), 2);
Imgproc.line(histImage, new Point(binW * (i - 1), histH - Math.round(gHistData[i - 1])),
new Point(binW * (i), histH - Math.round(gHistData[i])), new Scalar(0, 255, 0), 2);
Imgproc.line(histImage, new Point(binW * (i - 1), histH - Math.round(rHistData[i - 1])),
new Point(binW * (i), histH - Math.round(rHistData[i])), new Scalar(0, 0, 255), 2);
}
HighGui.imshow( "源图像", src );
HighGui.imshow( "calcHist 演示", histImage );
HighGui.waitKey(0);
System.exit(0);
}
}
public class CalcHistDemo {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
new CalcHist().run(args);
}
}