#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include
using namespace cv;
using namespace std;
//求九个数的中值
uchar Median(uchar n1, uchar n2, uchar n3, uchar n4, uchar n5,
uchar n6, uchar n7, uchar n8, uchar n9) {
uchar arr[9];
arr[0] = n1;
arr[1] = n2;
arr[2] = n3;
arr[3] = n4;
arr[4] = n5;
arr[5] = n6;
arr[6] = n7;
arr[7] = n8;
arr[8] = n9;
for (int gap = 9 / 2; gap > 0; gap /= 2)//希尔排序
for (int i = gap; i < 9; ++i)
for (int j = i - gap; j >= 0 && arr[j] > arr[j + gap]; j -= gap)
swap(arr[j], arr[j + gap]);
return arr[4];//返回中值
}
//图像椒盐化
void salt(Mat &image, int num) {
if (!image.data) return;//防止传入空图
int i, j;
srand(time(NULL));
for (int x = 0; x < num; ++x) {
i = rand() % image.rows;
j = rand() % image.cols;
image.at(i, j)[0] = 255;
image.at(i, j)[1] = 255;
image.at(i, j)[2] = 255;
}
}
//中值滤波函数
void MedianFlitering(const Mat &src, Mat &dst) {
if (!src.data)return;
//创建目标矩阵
Mat _dst(src.size(), src.type());
for (int i = 0; i < src.rows; ++i)
for (int j = 0; j < src.cols; ++j) {
if ((i - 1) > 0 && (i + 1) < src.rows && (j - 1) > 0 && (j + 1) < src.cols) {
_dst.at(i, j)[0] = Median(src.at(i, j)[0], src.at(i + 1, j + 1)[0],
src.at(i + 1, j)[0], src.at(i, j + 1)[0], src.at(i + 1, j - 1)[0],
src.at(i - 1, j + 1)[0], src.at(i - 1, j)[0], src.at(i, j - 1)[0],
src.at(i - 1, j - 1)[0]);
_dst.at(i, j)[1] = Median(src.at(i, j)[1], src.at(i + 1, j + 1)[1],
src.at(i + 1, j)[1], src.at(i, j + 1)[1], src.at(i + 1, j - 1)[1],
src.at(i - 1, j + 1)[1], src.at(i - 1, j)[1], src.at(i, j - 1)[1],
src.at(i - 1, j - 1)[1]);
_dst.at(i, j)[2] = Median(src.at(i, j)[2], src.at(i + 1, j + 1)[2],
src.at(i + 1, j)[2], src.at(i, j + 1)[2], src.at(i + 1, j - 1)[2],
src.at(i - 1, j + 1)[2], src.at(i - 1, j)[2], src.at(i, j - 1)[2],
src.at(i - 1, j - 1)[2]);
}
else
_dst.at(i, j) = src.at(i, j);
}
_dst.copyTo(dst);//拷贝
}
void main() {
Mat image = imread("F:/2.png");
Mat Salt_Image;
image.copyTo(Salt_Image);
salt(Salt_Image, 3000);
Mat image3, image4;
MedianFlitering(Salt_Image, image3);
medianBlur(Salt_Image, image4, 3);
imshow("图片椒盐化处理后", Salt_Image);
imshow("自定义中值滤波处理后", image3);
imshow("openCV自带的中值滤波", image4);
waitKey();
}