1. Calculate the histogram of an image.
// Calculate the histogram CV: matnd imagehist: gethist (const CV: mat & image) {CV: mat im; If (image. channels () = 3) CV: cvtcolor (image, Im, cv_rgb2gray, 0); elseim = image; float R [2]; R [0] = 0; R [1] = 255; const float * ranges [1]; ranges [0] = r; CV: calchist (& im, 1, & channels, CV :: MAT (), Hist, 1, & histsize, ranges); Return hist;} // generates the histogram to display the CV: mat imagehist :: gethistimage (const CV: mat & image) {double maxval = 0; double minval = 0; CV: minmaxloc (Hist, & minval, & maxval, 0, 0); CV :: mat histimg (histsize, histsize, cv_8u, CV: Scalar (255); int high = histsize * 0.9; For (INT I = 0; I 2. Remove the bin at both ends of the Histogram as 0 or smaller than a certain number of bins, and record the gray values (Mini, Maxi) at the two ends after removal ), then, use the following formula to stretch the color search table: (I-mini) * 255/(Maxi-mini) + 0.5
cv::Mat ImageHist::stretch(const cv::Mat &image,int minValue /* = 0 */){int mini = 0;for (;mini < histSize;++mini){if(hist.at<float>(mini) > minValue)break;}int maxi = histSize - 1;for (;maxi >= 0;--maxi){if(hist.at<float>(maxi) > minValue)break;}cv::Mat lookup(1,256,CV_8U);for (int i = 0;i < histSize;++i){if(i < mini)lookup.at<uchar>(i) = 0;else if(i > maxi)lookup.at<uchar>(i) = 255;elselookup.at<uchar>(i) =static_cast<uchar>((i - mini) * 255 / (maxi - mini) + 0.5);}cv::Mat result;cv::LUT(image,lookup,result);return result;}
Result: