//均值濾波器
//nWindowSize 爲濾波器窗口大小,取奇數。
// pSrcImage 指向原始圖像的指針。
//返回值是 指向處理後圖像的指針。
#include "StdAfx.h"
#include "filterfunction.h"
IplImage* meanfilter(const IplImage* pSrcImage,int nWindowSize)
{
int nRadius = (nWindowSize-1)/2;
//
if (pSrcImage->nChannels!=1)
{
MessageBox(NULL,"Images with more than one channel are not surpported yet.^_^", "Error", MB_OK);
//handle error here
return 0;
}
//handle image with one channel
IplImage* pDesImage = cvCloneImage(pSrcImage);
int nSumWindow = 0;
for (int i = nRadius; i < pSrcImage->height-nRadius; i++)
{
for (int j = nRadius; j < pSrcImage->widthStep-nRadius; j++)
{
nSumWindow = 0;
for (int m = -nRadius; m <= nRadius; m++)
{
for (int n = -nRadius; n <= nRadius; n++)
{
nSumWindow = nSumWindow + (unsigned char) (pSrcImage->imageData[pSrcImage->widthStep*(i+m)+j+n]);
}
}
pDesImage->imageData[pDesImage->widthStep*i + j] = (unsigned char)(nSumWindow/(nWindowSize*nWindowSize));
}
}
return pDesImage;
}
//中值濾波器
#include "StdAfx.h"
#include "filterfunction.h"
unsigned char FindMedianValue(unsigned char* array,int nLength);
IplImage* medianfilter(const IplImage* pSrcImage,int nWindowSize)
{
int nRadius = (nWindowSize-1)/2;
//
if (pSrcImage->nChannels!=1)
{
MessageBox(NULL,"Images with more than one channel are not surpported yet.^_^", "Error", MB_OK);
//handle error here
return 0;
}
//handle image with one channel
IplImage* pDesImage = cvCloneImage(pSrcImage);
unsigned char* pWindowData = new unsigned char[nWindowSize*nWindowSize];
memset(pWindowData,0,nWindowSize*nWindowSize*sizeof(char));
unsigned char* ptemp = pWindowData;
for (int i = nRadius; i < pSrcImage->height-nRadius; i++)
{
for (int j = nRadius; j < pSrcImage->widthStep-nRadius; j++)
{
ptemp = pWindowData;
for (int m = -nRadius;m <= nRadius;m++)
{
for (int n = -nRadius;n <= nRadius;n++)
{
*ptemp = (unsigned char) (pSrcImage->imageData[pSrcImage->widthStep*(i+m)+j+n]);
ptemp++;
}
}
pDesImage->imageData[pSrcImage->widthStep*i+j] = FindMedianValue(pWindowData,nWindowSize*nWindowSize);
}
}
//delete pWindowData;
return pDesImage;
}
unsigned char FindMedianValue(unsigned char* array,int nLength)
{
//冒泡
unsigned char* ptemp = array;
unsigned char ntemp = 0;
for (int i = 0;i < nLength;i++)
{
ptemp = array;
for (int j = 0;j < nLength-i;j++)
{
if(*ptemp > *(ptemp+1))
{
ntemp = *ptemp;
*ptemp = *(ptemp+1);
*(ptemp+1) = ntemp;
ptemp++;
}else
ptemp++;
}
}
return *(array+(nLength-1)/2);
}