知识点
图像直方图均衡化
图像直方图均衡化可以用于图像增强、对输入图像进行直方图均衡化处理,提升后续对象检测的准确率在OpenCV人脸检测的代码演示中已经很常见。此外对医学影像图像与卫星遥感图像也经常通过直方图均衡化来提升图像质量。
OpenCV中直方图均衡化的API很简单
- equalizeHist(src, dst)
python代码
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("C:/Users/qqxd/Desktop/opencvcode/images/flower.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()
c++代码
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int artc, char** argv) {
Mat src = imread("C:/Users/qqxd/Desktop/opencvcode/images/flower.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
Mat gray, dst;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow("input", gray);
equalizeHist(gray, dst);
imshow("eq", dst);
waitKey(0);
return 0;
}
运行结果如下: