-
Notifications
You must be signed in to change notification settings - Fork 0
/
MedianFilter.cpp
57 lines (53 loc) · 1.16 KB
/
MedianFilter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "canny.h"
void BublleSort(vector<uint16> &arr)
{
bool flag = true;
for (uint16 i = 0; i < arr.size() - 1; ++i)
{
while (flag)
{
flag = false;
for (uint16 j = 0; j < arr.size() - 1 - i; ++j)
{
if (arr[j] > arr[j + 1])
{
uint16 tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = true;
}
}
}
}
}
void MedianFilter(Mat& src, Mat& dst, uint16 size)
{
//图像边界扩充
if (size % 2 == 0)
{
fprintf(stderr, "Please enter odd size!");
exit(-1);
}
uint16 hh = (size - 1) / 2;
uint16 hw = (size - 1) / 2;
Mat Newsrc;
copyMakeBorder(src, Newsrc, hh, hh, hw, hw, BORDER_REFLECT);//边缘扩充
dst = Mat::zeros(src.rows, src.cols, src.type());
//中值滤波
for (uint16 i = hh; i < src.rows + hh - 1; i++)
{
uint8* ptrdst = dst.ptr(i - hh);
for (uint16 j = hw; j < src.cols + hw - 1; j++)
{
vector<uint16> pix;
for (uint16 r = i - hh; r <= i + hh; r++)
{
const uint8* ptrsrc = Newsrc.ptr(r);
for (uint16 c = j - hw; c <= j + hw; c++)
pix.push_back(ptrsrc[c]);
}
BublleSort(pix);//冒泡排序
ptrdst[j - hw] = pix[(pow(size, 2) - 1) / 2];//将中值映射到输出图像
}
}
}