/*** (1). implementing histogram equalization for image enhancement ***/ bool HistogramEqualization( IplImage* pSrcImg, //@pSrcImg : input gray image IplImage*& pDstImg, //@pDstImg : output histogram equalized gray image IplImage*& pSrcHistImg,//@pSrcHistImg: original histogram of the input IplImage*& pDstHistImg)//@pDstHistImg: equalized histogram of the output { if(!pSrcImg) return false; //create two histogram images pSrcHistImg = cvCreateImage(cvSize(256, 256), 8, 1); pDstHistImg = cvCreateImage(cvSize(256, 256), 8, 1); /*** YOUR CODE HERE ***/ //[50pts] return true; }
时间: 2023-05-29 19:04:08 浏览: 109
pDstImg ) //@pDstImg : output equalized gray image
{
if( !pSrcImg || !pDstImg ) //check if input and output images are valid
return false;
if( pSrcImg->nChannels != 1 || pDstImg->nChannels != 1 ) //check if images are grayscale
return false;
int hist[256] = {0}; //initialize histogram array with zeros
//calculate histogram
for( int i = 0; i < pSrcImg->height; i++ )
{
uchar* ptr = (uchar*)(pSrcImg->imageData + i * pSrcImg->widthStep);
for( int j = 0; j < pSrcImg->width; j++ )
{
hist[ptr[j]]++;
}
}
int cumHist[256] = {0}; //initialize cumulative histogram array with zeros
int totalPixels = pSrcImg->width * pSrcImg->height; //calculate total number of pixels in the image
cumHist[0] = hist[0];
for( int i = 1; i < 256; i++ )
{
cumHist[i] = cumHist[i-1] + hist[i]; //calculate cumulative histogram
}
//normalize cumulative histogram
for( int i = 0; i < 256; i++ )
{
cumHist[i] = (int)(((float)cumHist[i] / totalPixels) * 255 + 0.5);
}
//perform histogram equalization
for( int i = 0; i < pSrcImg->height; i++ )
{
uchar* ptrSrc = (uchar*)(pSrcImg->imageData + i * pSrcImg->widthStep);
uchar* ptrDst = (uchar*)(pDstImg->imageData + i * pDstImg->widthStep);
for( int j = 0; j < pSrcImg->width; j++ )
{
ptrDst[j] = cumHist[ptrSrc[j]]; //map pixel values to equalized values
}
}
return true; //return success
}
阅读全文