opencv4.0.0图像处理:图像直方图(七)

图像直方图反映了图像像素的密度分布,下面是BGR图像三通道的直方图测试

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;
//MatOfInt channels = new MatOfInt(0);

boolean accumulate = false;

//Mat histImg1 = new Mat();
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);
}

//imshow(histImage, "histImage");
HighGui.imshow("histImage", histImage);
HighGui.imshow("hello", hello);
HighGui.waitKey(0);
System.exit(0);

}



观察上面的直方图可以看到,blue通道与green通道的直方图偏向左边,而red通道的直方图偏向右边;如果我们显示单通道的图像,估计blue通道与green通道的图像偏黑,而red通道的图像偏白

坚持原创技术分享,您的支持是我前进的动力!