中值滤波容易去除孤立点,线的噪声同时保持图象的边缘;它能很好的去除二值噪声,但对高斯噪声无能为力
#include "cv.h"
#include "highgui.h"
using namespace cv;
#define PI 3.1415926
#define RADIAN(angle) ((angle)*PI/180.0)
int smooth_box[9]={1,1,1,1,1,1,1,1,1};
int smooth_gauss[9]={1,2,1,2,4,2,1,2,1};
int sharpen_laplacian[9]={-1,-1,-1,-1,9,-1,-1,-1,-1};
//平滑和锐化
Mat TemplateOP(Mat& mat)
{
int M=mat.rows;
int N=mat.cols;
float coef;
int coefArray[9];
#if 0
coef=(float)(1.0/9.0);
memcpy(coefArray,smooth_box,sizeof(smooth_box));
#elif 0
coef=(float)(1.0/16.0);
memcpy(coefArray,smooth_gauss ,sizeof(smooth_gauss));
#else
coef=(float)1.0;
memcpy(coefArray,sharpen_laplacian,sizeof(sharpen_laplacian));
#endif
Mat ret(M,N,CV_8U);
for(int i=1;i<M-1;i++)
{
for(int j=1;j<N-1;j++)
{
float tempNum=0.0;
int k=0;
for(int i1=-1;i1<=1;i1++)
for(int j1=-1;j1<=1;j1++)
tempNum+=mat.ptr<uchar>(i+i1)[j+j1]*coefArray[k++];
tempNum*=coef;
uchar temp;
if(tempNum>255.0) temp=255;
else if(tempNum<0.0) temp=0;
else temp=(uchar)tempNum;
ret.ptr<uchar>(i)[j]=temp;
}
}
return ret;
}
//中值滤波
Mat MedianFilter(Mat& mat)
{
int M=mat.rows;
int N=mat.cols;
vector<int> nums(9,0);
Mat ret(M,N,CV_8U);
for(int i=1;i<M-1;i++)
{
for(int j=1;j<N-1;j++)
{
int k=0;
for(int i1=-1;i1<=1;i1++)
for(int j1=-1;j1<=1;j1++)
nums[k++]=mat.ptr<uchar>(i+i1)[j+j1];
sort(nums.begin(),nums.end());
ret.ptr<uchar>(i)[i]=nums[4];
}
}
return ret;
}
int main()
{
//读取图像
Mat image;
image=imread("circle.jpg",CV_LOAD_IMAGE_GRAYSCALE);
int M=image.rows;
int N=image.cols;
//几何变换
Mat newImage=TemplateOP(image);
cvNamedWindow("test",CV_WINDOW_AUTOSIZE);
imshow("test",newImage);
waitKey(0);
return 0;
}
794

被折叠的 条评论
为什么被折叠?



