Article 5 — Appendix A.2
Mean filter, or average filter source code
Download mean filter C++ source code (zip, 2 Kb)
meanfilter.cpp
#include <memory.h>
#include "meanfilter.h"
void _meanfilter(const element* signal, element* result, int N)
{
for (int i = 2; i < N - 2; ++i)
result[i - 2] = (
signal[i - 2] +
signal[i - 1] +
signal[i] +
signal[i + 1] +
signal[i + 2]) / 5;
}
void meanfilter(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];
}
_meanfilter(extension, result ? result : signal, N + 4);
delete[] extension;
}
void _meanfilter(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)
result[(m - 1) * (N - 2) + n - 1] = (
image[(m - 1) * N + n - 1] +
image[(m - 1) * N + n] +
image[(m - 1) * N + n + 1] +
image[m * N + n - 1] +
image[m * N + n] +
image[m * N + n + 1] +
image[(m + 1) * N + n - 1] +
image[(m + 1) * N + n] +
image[(m + 1) * N + n + 1]) / 9;
}
void meanfilter(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));
_meanfilter(extension, result ? result : image, N + 2, M + 2);
delete[] extension;
}
|