1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public static void main(String[] args) { Mat hello =Imgcodecs.imread("data/lena.jpg"); List<Mat> bgrPlanes = new ArrayList<>(); Core.split(hello, bgrPlanes); MatOfFloat histRange = new MatOfFloat(0, 256); int histSize = 256;
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( 255,255,255) ); Core.normalize(bHist, bHist, 0, histImage.rows()-20, Core.NORM_MINMAX); Core.normalize(gHist, gHist, 0, histImage.rows()-20, Core.NORM_MINMAX); Core.normalize(rHist, rHist, 0, histImage.rows()-20, Core.NORM_MINMAX); float[] bHistData = new float[(int) (bHist.total() * bHist.channels())]; bHist.get(0, 0, bHistData); System.out.println(Arrays.toString(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("histImage", histImage); HighGui.imshow("hello", hello); HighGui.waitKey(0); System.exit(0); }
|