直方图均衡化代码c++
时间: 2024-04-21 07:20:15 浏览: 26
直方图均衡化是一种用于增强图像对比度的方法,它通过重新分布图像的像素值来实现。下面是一个简单的C++代码示例:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
// 读取图像
Mat image = imread("input.jpg", IMREAD_GRAYSCALE);
if (image.empty()) {
cout << "无法读取图像" << endl;
return -1;
}
// 计算直方图
int histSize = 256;
float range[] = {0, 256};
const float* histRange = {range};
bool uniform = true, accumulate = false;
Mat hist;
calcHist(&image, 1, 0, Mat(), hist, 1, &histSize, &histRange, uniform, accumulate);
// 计算累积直方图
Mat cumulativeHist(histSize, 1, CV_32F);
cumulativeHist.at<float>(0) = hist.at<float>(0);
for (int i = 1; i < histSize; i++) {
cumulativeHist.at<float>(i) = cumulativeHist.at<float>(i - 1) + hist.at<float>(i);
}
// 归一化累积直方图
cumulativeHist /= image.total();
// 映射像素值
Mat equalizedImage = image.clone();
for (int i = 0; i < image.rows; i++) {
for (int j = 0; j < image.cols; j++) {
int pixelValue = image.at<uchar>(i, j);
equalizedImage.at<uchar>(i, j) = cvRound(cumulativeHist.at<float>(pixelValue) * 255);
}
}
// 显示原始图像和均衡化后的图像
namedWindow("Original Image", WINDOW_NORMAL);
namedWindow("Equalized Image", WINDOW_NORMAL);
imshow("Original Image", image);
imshow("Equalized Image", equalizedImage);
waitKey(0);
return 0;
}
```
这段代码使用OpenCV库来实现直方图均衡化。首先,它读取一张灰度图像,并计算其直方图。然后,计算累积直方图,并将其归一化。最后,通过映射像素值,生成均衡化后的图像。最后,原始图像和均衡化后的图像将在窗口中显示出来。