#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
cv::Mat contrastStretch(cv::Mat srcImage)
{
cv::Mat resultImage = srcImage.clone();
int nRows = resultImage.rows;
int nCols = resultImage.cols;
if(resultImage.isContinuous())
{
nCols = nCols * nRows;
nRows = 1;
}
uchar *pDataMat;
int pixMax = 0, pixMin = 255;
for(int j = 0; j <nRows; j ++)
{
pDataMat = resultImage.ptr<uchar>(j);
for(int i = 0; i < nCols; i ++)
{
if(pDataMat[i] > pixMax)
pixMax = pDataMat[i];
if(pDataMat[i] < pixMin)
pixMin = pDataMat[i];
}
}
for(int j = 0; j < nRows; j ++)
{
pDataMat = resultImage.ptr<uchar>(j);
for(int i = 0; i < nCols; i ++)
{
pDataMat[i] = (pDataMat[i] - pixMin) *
255 / (pixMax - pixMin);
}
}
return resultImage;
}
int main()
{
cv::Mat srcImage = cv::imread("lakeWater.jpg");
if(!srcImage.data)
return 0;
cv::Mat srcGray;
cvtColor(srcImage, srcGray, CV_BGR2GRAY);
imshow("srcGray", srcGray);
cv::Mat resultImage = contrastStretch(srcGray);
cv::imshow("resultImage", resultImage);
cv::waitKey(0);
return 0;
}
可以用自带的函数实现
CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray());