Often, we want to do some grayscale transformation of gray image. such as the enhancement of contrast-type. OpenCV does not directly provide functions to handle. We need to write a little bit of code. Here are a few pieces of code that I often use.
Today's code uses some of the functionality of previously written code. The specific can be consulted:
http://blog.csdn.net/liyuanbhu/article/details/50708912
The first is histogram normalization. The so-called histogram regularization, is the image of the darkest place in the brightness set to 0, the brightest place of brightness set to 255, other places of brightness linear mapping.
cv::Mat Histogram1D::normalize(const cv::Mat &image){ // Compute histogram first cv::MatND hist = getHistogram(image); int imin, imax; for(imin = 0; imin < histSize[0]; imin++) { if(hist.at<float>(imin) > 0) break; } for(imax = histSize[0] - 1; imax >= 0; imax--) { if(hist.at<float>(imax) > 0) break; } cv::Mat lookup(1, 256, CV_8U); for(int i = 0; i < 256; i++) { if(i < imin) lookup.at<uchar>(i) = 0; else if(i > imax) lookup.at<uchar>(i) = 255; else { int v = 255 * (i - imin) / (imax - imin); lookup.at<uchar>(i) = static_cast<uchar>(v); } } cv::Mat ret; cv::LUT(image, lookup, ret); return ret;}
Then there is a common method of image enhancement. The grayscale value is stretched. Simply discard the brightest and darkest portions of the luminance histogram and stretch the rest to 0 to 255.
Here's the code:
Cv::mat histogram1d::stretch (const Cv::mat &image, double percent1, double percent2) {Cv::matnd hist = Gethistogram (image); int Imin, IMAX; if (Percent1 < 0.0) Percent1 = 0.0; if (Percent1 > 1.0) percent1 = 1.0; Percent1 = image.rows * Image.cols * PERCENT1; Double value = 0; for (imin = 0; imin < histsize[0]; imin++) {Value + = hist.at<float> (imin); if (value > Percent1) break; } value = 0; if (Percent2 < 0.0) Percent2 = 0.0; if (Percent2 > 1.0) Percent2 = 1.0; Percent2 = image.rows * Image.cols * PERCENT2; for (IMAX = histsize[0]-1; IMAX >= 0; imax--) {Value + = hist.at<float> (IMAX); if (value > Percent2) break; }//int Dim = 256; Cv::mat lookup (1, cv_8u); for (int i = 0; i < i++) {if (I < imin) lookup.at<uchar> (i) = 0; else if (i > Imax) lookup.at<uchar> (i) = 255; else {int v = 255 * (i-imin)/(Imax-imin); Lookup.at<uchar> (i) = static_cast<uchar> (v); }} cv::mat ret; Cv::lut (image, lookup, ret); return ret;} Cv::mat histogram1d::stretch (const Cv::mat &image, double percent) {return stretch (image, percent, percent);}
The code is very simple answer, not much explanation.
Some codes of gray-scale image histogram transformation