Last active
August 29, 2015 14:13
-
-
Save goldsborough/98c2af6d41d105cd0d38 to your computer and use it in GitHub Desktop.
1-D Median Filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
std::vector<double> medianFilter_(const std::vector<double>& array, unsigned long window) | |
{ | |
std::vector<double> filtered; | |
filtered.reserve(array.size()); | |
unsigned long middle = window / 2; | |
std::vector<double>::const_iterator itr, end, first, last, firstMid, lastMid; | |
// first is the start of the current | |
// median filter window and itr is | |
// and iterator to check for positioning | |
first = itr = array.begin(); | |
// After this point the first iterator | |
// starts incrementing | |
firstMid = array.begin() + middle; | |
// The end of the current median | |
// filter window | |
last = firstMid + 1; | |
// The end of the array | |
end = array.end(); | |
// After this point the last iterator | |
// stops incrementing | |
lastMid = end - middle; | |
// For odd windows the last iterator | |
// stops incrementing earlier, because | |
// for even windows the iterator starts | |
// at the right of the two middle values | |
// and thus needs an extra incrementing | |
if (window % 2) --lastMid; | |
for( ; itr != end; ++itr) | |
{ | |
// Current window | |
std::vector<double> temp(first,last); | |
std::sort(temp.begin(), temp.end()); | |
// This middle value cannot be precomputed | |
// because the window size varies at the | |
// begininning and end | |
middle = temp.size() / 2; | |
double median; | |
// If the temporary array has an even size | |
if (! (temp.size() % 2)) | |
{ | |
// Median for even sizes | |
median = (temp[middle] + temp[middle - 1]) / 2.0; | |
} | |
else median = temp[middle]; // Median for odd numbers | |
filtered.push_back(median); | |
// Start incrmenting first after firstMid | |
if (itr >= firstMid) ++first; | |
// Stop incrementing last after lastMid | |
if (itr < lastMid) ++last; | |
} | |
return filtered; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment