关于中值滤波的原理和相关准备知识参考以下博文
https://blog.csdn.net/baidu_38172402/article/details/81904605
但是原博给出的代码段并不完整,许多细节并未呈现,导致运行出错,以下给出本人完善改进后的代码
#include<iostream>
#include<opencv2/opencv.hpp>
#include <math.h>
using namespace std;
using namespace cv;
//own median filter algorithm
int main()
{
Mat src, dst;
int arr[9];
src = imread("D:/test/4.jpg");
imshow("src", src);
dst = Mat::zeros(src.size(),src.type());
const int offsetx = src.channels();
const int nc = src.cols * offsetx;
for (int i = 1; i < (src.rows - 1); i++) //遍历行
{
uchar * previous = src.ptr<uchar>(i - 1);
uchar * current = src.ptr<uchar>(i);
uchar * next = src.ptr<uchar>(i + 1);
uchar * output = dst.ptr<uchar>(i);
for (int j = offsetx; j <(nc - 1); j++)//遍历列
{
for (int k = 0; k < 3; k++)
{
arr[k] = previous[j-offsetx];
arr[k + 3] = current[j];
arr[k + 6] = next[j + offsetx];
}
void bubble_sort(int* arr, int num);
bubble_sort(arr, 9);
output[j] = arr[4];
}
}
//set the pixels on the borders to zeros
int s = dst.rows - 1;
int n = dst.cols - 1;
dst.row(0).setTo(Scalar(0));
dst.row(s).setTo(Scalar(0));
dst.col(0).setTo(Scalar(0));
dst.col(n).setTo(Scalar(0));
//show the result
imshow("dst", dst);
waitKey(0);
return 0;
}
void bubble_sort(int *arr, int num)
{
int temp=0;
for (int i=1;i<num-1;i++)
{
for (int j = 0; j<num-i;j++)
{
if (arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
新手入门,如有错误还请多多指正。