直方图变换-----累计

来源:互联网 发布:java 获取版本号 编辑:程序博客网 时间:2024/04/28 20:18
直方图变换累计的方法:
1.将源图像转化为灰度图,计算图像的灰度直方图
2.建立映射表,对直方图进行像素累计
3.根据映射表进行元素映射得到最终的直方图变换

代码如下:

#include "opencv2/highgui/highgui.hpp"#include "opencv2/imgproc/imgproc.hpp"#include "opencv2/opencv.hpp"#include "opencv2/core/core.hpp"#include <stdio.h>#include <string>using namespace std;using namespace cv;int main(){cv::Mat srcImage = cv::imread("C:\\Users\\LP\\Desktop\\C++\\ConsoleApplication4\\ConsoleApplication4\\RGBFlower4.jpg");if (srcImage.empty()){return -1;} cv::imshow("原图像", srcImage);//转换为灰度图cv::Mat srcGray;cv::cvtColor(srcImage, srcGray, CV_RGB2GRAY);//计算图像直方图const int channels[1] = {0};const int histSize[1] = {256};float hranges[2] = {0, 255};const float* ranges[1] = {hranges};cv::MatND hist;cv::calcHist(&srcGray, 1, channels, cv::Mat(), hist, 1, histSize, ranges);float table[256];int nPix = srcGray.cols * srcGray.rows;//建立映射表for (int i = 0; i < 256; i++){float temp[256];//像素变换temp[i] = hist.at<float>(i) / nPix * 255;if (i != 0){//像素累计table[i] = table[i - 1] + temp[i];}else{table[i] = temp[i];}}//通过映射表查找cv::Mat lookUpTable(cv::Size(1, 256), CV_8U);for (int i = 0; i < 256; i++){lookUpTable.at<uchar>(i) = static_cast<uchar>(table[i]);}cv::Mat histTransResult;cv::LUT(srcGray, lookUpTable, histTransResult);cv::imshow("histTransResult", histTransResult);cv::waitKey(0);return 0;}