Article 1 — Appendix A.2
Median filter source code
Download median filter C++ source code (zip, 2 Kb)
medianfilter.cpp
#include <memory.h>
#include "medianfilter.h"
void _medianfilter(const element* signal, element* result, int N)
{
for (int i = 2; i < N - 2; ++i)
{
element window[5];
for (int j = 0; j < 5; ++j)
window[j] = signal[i - 2 + j];
for (int j = 0; j < 3; ++j)
{
int min = j;
for (int k = j + 1; k < 5; ++k)
if (window[k] < window[min])
min = k;
const element temp = window[j];
window[j] = window[min];
window[min] = temp;
}
result[i - 2] = window[2];
}
}
void medianfilter(element* signal, element* result, int N)
{
if (!signal || N < 1)
return;
if (N == 1)
{
if (result)
result[0] = signal[0];
return;
}
element* extension = new element[N + 4];
if (!extension)
return;
memcpy(extension + 2, signal, N * sizeof(element));
for (int i = 0; i < 2; ++i)
{
extension[i] = signal[1 - i];
extension[N + 2 + i] = signal[N - 1 - i];
}
_medianfilter(extension, result ? result : signal, N + 4);
delete[] extension;
}
void _medianfilter(const element* image, element* result, int N, int M)
{
for (int m = 1; m < M - 1; ++m)
for (int n = 1; n < N - 1; ++n)
{
int k = 0;
element window[9];
for (int j = m - 1; j < m + 2; ++j)
for (int i = n - 1; i < n + 2; ++i)
window[k++] = image[j * N + i];
for (int j = 0; j < 5; ++j)
{
int min = j;
for (int l = j + 1; l < 9; ++l)
if (window[l] < window[min])
min = l;
const element temp = window[j];
window[j] = window[min];
window[min] = temp;
}
result[(m - 1) * (N - 2) + n - 1] = window[4];
}
}
void medianfilter(element* image, element* result, int N, int M)
{
if (!image || N < 1 || M < 1)
return;
element* extension = new element[(N + 2) * (M + 2)];
if (!extension)
return;
for (int i = 0; i < M; ++i)
{
memcpy(extension + (N + 2) * (i + 1) + 1,
image + N * i,
N * sizeof(element));
extension[(N + 2) * (i + 1)] = image[N * i];
extension[(N + 2) * (i + 2) - 1] = image[N * (i + 1) - 1];
}
memcpy(extension,
extension + N + 2,
(N + 2) * sizeof(element));
memcpy(extension + (N + 2) * (M + 1),
extension + (N + 2) * M,
(N + 2) * sizeof(element));
_medianfilter(extension, result ? result : image, N + 2, M + 2);
delete[] extension;
}
|