opencv-018-图像直方图均衡化

知识点

图像直方图均衡化可以用于图像增强、对输入图像进行直方图均衡化处理,提升后续对象检测的准确率,在OpenCV人脸检测的代码演示中已经很常见。此外对医学影像图像与卫星遥感图像也经常通过直方图均衡化来提升图像质量。

API

equalizeHist(src, dst)

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 图像直方图均衡化
*/
int main() {
Mat src = imread("../images/test.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}

Mat gray, dst;
cvtColor(src, gray, COLOR_BGR2GRAY);
equalizeHist(gray, dst);
imshow("input", gray);
imshow("eq", dst);

waitKey(0);
return 0;
}
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
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt


def custom_hist(gray):
h, w = gray.shape
hist = np.zeros([256], dtype=np.int32)
for row in range(h):
for col in range(w):
pv = gray[row, col]
hist[pv] += 1

y_pos = np.arange(0, 256, 1, dtype=np.int32)
plt.bar(y_pos, hist, align='center', color='r', alpha=0.5)
plt.xticks(y_pos, y_pos)
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()


src = cv.imread("../images/test.png")
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", gray)
dst = cv.equalizeHist(gray)
cv.imshow("eh", dst)

custom_hist(gray)
custom_hist(dst)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github