# 图像平滑之平均平滑

#include <iostream>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
using namespace std;
using namespace cv;

//常用滤波模板数组
//平均平滑1/9
float Template_Smooth_Avg[9] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
/****************************************************************************************************

*****************************************************************************************************/
void Template(Mat img,Mat &dst, int nTempH, int nTempW, int nTempMY, int nTempMX, float *pfArray, float fCoef)
{
int i, j;
//#pragma omp parallel for
for (i = nTempMY; i < img.rows - (nTempH - nTempMY) + 1; i++)
{
for (j = nTempMX; j < img.cols - (nTempW - nTempMX) + 1; j++)
{
float fResult1 = 0;
float fResult2 = 0;
float fResult3 = 0;
//#pragma omp parallel for
for (int k = 0; k < nTempH; k++)
{
for (int l = 0; l < nTempW; l++)
{
//#pragma omp critical
//{
fResult1 += img.at<Vec3b>(i + l - nTempMX, j + k - nTempMY)[0] * pfArray[k*nTempH + l];
fResult2 += img.at<Vec3b>(i + l - nTempMX, j + k - nTempMY)[1] * pfArray[k*nTempH + l];
fResult3 += img.at<Vec3b>(i + l - nTempMX, j + k - nTempMY)[2] * pfArray[k*nTempH + l];
//}
}
}
fResult1 *= fCoef;
fResult1 = (float)fabs(fResult1);
fResult2 *= fCoef;
fResult2 = (float)fabs(fResult2);
fResult3 *= fCoef;
fResult3 = (float)fabs(fResult3);

//#pragma omp critical
//{
dst.at<Vec3b>(i, j)[0] = (fResult1>255) ? 255 : (fResult1 + 0.5);
dst.at<Vec3b>(i, j)[1] = (fResult2>255) ? 255 : (fResult2 + 0.5);
dst.at<Vec3b>(i, j)[2] = (fResult3>255) ? 255 : (fResult3 + 0.5);
//}
}
}
}
void main()
{
cvNamedWindow("原图", CV_WINDOW_FREERATIO);
imshow("原图", img);
Mat dst=img.clone();
Template(img, dst, 3, 3, 1, 1, Template_Smooth_Avg, (float)1 / 9);
cvNamedWindow("平均平滑", CV_WINDOW_FREERATIO);
imshow("平均平滑", dst);
waitKey(0);
}