cv::Mat histogramEqualization(cv::Mat img){ int rows=img.rows; int cols=img.cols; cv::Mat grayScale=cv::Mat::zeros(cv::Size(256,1),CV_32SC1); cv::Mat grayScaleSum=cv::Mat::zeros(cv::Size(256,1),CV_32SC1); cv::Mat _output=cv::Mat::zeros(cv::Size(256,1),CV_8UC1); cv::Mat output=cv::Mat::zeros(img.size(),CV_8UC1); float cofficient=256.0/(rows*cols); for(int i=0;i<rows;++i){ // 计算不同灰度值的个数。 for(int j=0;j<cols;++j){ int index=int(img.at<uchar>(i,j)); grayScale.at<int>(0,index)+=1; } } for(int j=0;j<256;++j){ if(j==0)grayScaleSum.at<int>(0,j)=grayScale.at<int>(0,0); else grayScaleSum.at<int>(0,j)=grayScaleSum.at<int>(0,j-1)+grayScale.at<int>(0,j); } for(int i=0;i<256;++i){ float q=cofficient*grayScaleSum.at<int>(0,i)-1; if(q>=0)_output.at<uchar>(0,i)=uchar(floor(q)); // floor(x)Largest integer not greater than X. else _output.at<uchar>(0,i)=0; } for(int i=0;i<rows;++i){ for(int j=0;j<cols;++j){ int p=img.at<uchar>(i,j); output.at<uchar>(i,j)=_output.at<uchar>(0,p); } } return output; } int main(){ cv::Mat img=cv::imread("/home/nan/图片/openimage/girl.jpg",cv::IMREAD_GRAYSCALE); cv::imshow("img",img); //cv::Mat output= equalHist(img); cv::Mat output= histogramEqualization(img); cv::imshow("全局直方图均衡化",output); cv::waitKey(0); return 0; }