均值滤波:利用点(x,y)领域内像素点均值来替换(x,y)处像素值;
中值滤波:利用点(x,y)领域内像素点中值来替换(x,y)处像素值;
具体实现代码如下:
#include <opencv2/opencv.hpp>
using namespace cv;
const int directions[8][2] = { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, 1 },
{ 1, 1 }, { 1, 0 }, { 1, -1 }, {0, -1} };
void BubbleSort(int* ori, int length)
{
int temp = 0;
for (int i = 0; i < length - 1; i++)
for (int j = i + 1; j < length; j++)
{
if (ori[i] > ori[j])
{
temp = ori[i];
ori[i] = ori[j];
ori[j] = temp;
}
}
}
int main()
{
Mat src = imread("1.jpg");
Mat gray;
cvtColor(src, gray, CV_BGR2GRAY);
Mat Ave_filter = Mat::zeros(gray.rows, gray.cols, CV_8UC1);
int i, j, k;
float temp = 0;
// 均值滤波
for (i = 1; i < gray.rows - 1; i++)
for (j = 1; j < gray.cols - 1; j++)
{
for (k = 0; k < 8; k++)
{
temp += gray.at<uchar>(i + directions[k][0], j + directions[k][1]);
}
temp /= 8;
Ave_filter.at<uchar>(i, j) = temp;
}
Mat Med_filter = Mat::zeros(gray.rows, gray.cols, CV_8UC1);
// 中值滤波
int neighbors[8] = { 0 };
for (i = 1; i < gray.rows - 1; i++)
for (j = 1; j < gray.cols - 1; j++)
{
for (k = 0; k < 8; k++)
{
neighbors[k] = gray.at<uchar>(i + directions[k][0], j + directions[k][1]);
}
BubbleSort(neighbors, 8);
Med_filter.at<uchar>(i, j) = (neighbors[3] + neighbors[4])/2;
}
//imshow("src", gray);
imshow("ave", Ave_filter);
imshow("med", Med_filter);
waitKey();
return 0;
}
效果如下: