Article 8 — Appendix A.2
Hybrid median filter source code
Download hybrid median filter C++ source code (zip, 2 Kb)
hybridmedianfilter.cpp
#include <memory.h>
#include "hybridmedianfilter.h"
element median(element* elements, int N)
{
for (int i = 0; i < (N >> 1) + 1; ++i)
{
int min = i;
for (int j = i + 1; j < N; ++j)
if (elements[j] < elements[min])
min = j;
const element temp = elements[i];
elements[i] = elements[min];
elements[min] = temp;
}
return elements[N >> 1];
}
void _hybridmedianfilter(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)
{
element window[5];
element results[3];
window[0] = image[(m - 1) * N + n];
window[1] = image[m * N + n - 1];
window[2] = image[m * N + n];
window[3] = image[m * N + n + 1];
window[4] = image[(m + 1) * N + n];
results[0] = median(window, 5);
window[0] = image[(m - 1) * N + n - 1];
window[1] = image[(m - 1) * N + n + 1];
window[2] = image[m * N + n];
window[3] = image[(m + 1) * N + n - 1];
window[4] = image[(m + 1) * N + n + 1];
results[1] = median(window, 5);
results[2] = image[m * N + n];
result[(m - 1) * (N - 2) + n - 1] = median(results, 3);
}
}
void hybridmedianfilter(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));
_hybridmedianfilter(extension, result ? result : image, N + 2, M + 2);
delete[] extension;
}
|