Last active
September 10, 2020 15:50
-
-
Save khanh101/fdf4717561f453e80b731c829b559cbb to your computer and use it in GitHub Desktop.
median filter
This file contains 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
template<typename type> | |
inline void swap_sort(type& a, type& b) { | |
if (a > b) { | |
type temp = a; | |
a = b; | |
b = temp; | |
} | |
} | |
#include<array> | |
// source: http://ndevilla.free.fr/median/median.pdf | |
template<typename dtype> | |
inline dtype median9(std::array<dtype, 9> arr) { | |
swap_sort(arr[1], arr[2]); | |
swap_sort(arr[4], arr[5]); | |
swap_sort(arr[7], arr[8]); | |
swap_sort(arr[0], arr[1]); | |
swap_sort(arr[3], arr[4]); | |
swap_sort(arr[6], arr[7]); | |
swap_sort(arr[1], arr[2]); | |
swap_sort(arr[4], arr[5]); | |
swap_sort(arr[7], arr[8]); | |
swap_sort(arr[0], arr[3]); | |
swap_sort(arr[5], arr[8]); | |
swap_sort(arr[4], arr[7]); | |
swap_sort(arr[3], arr[6]); | |
swap_sort(arr[1], arr[4]); | |
swap_sort(arr[2], arr[5]); | |
swap_sort(arr[4], arr[7]); | |
swap_sort(arr[4], arr[2]); | |
swap_sort(arr[6], arr[4]); | |
swap_sort(arr[4], arr[2]); | |
return arr[4]; | |
} | |
template<typename dtype, typename itype> | |
void median_filter(dtype* dst, const dtype* src, itype height, itype width) { | |
for (itype h=0; h<height; h++) | |
for (itype w=0; w<width; w++) { | |
if (h == 0 or h == height-1 or w == 0 or w == width-1) | |
dst[h*width+w] = src[h*width+w]; | |
else { | |
std::array<dtype, 9> arr = { | |
src[h*width+w], | |
src[h*width+w+1], | |
src[h*width+w-1], | |
src[(h+1)*width+w], | |
src[(h-1)*width+w], | |
src[(h+1)*width+w+1], | |
src[(h+1)*width+w-1], | |
src[(h-1)*width+w+1], | |
src[(h-1)*width+w-1], | |
}; | |
dst[h*width+w] = median9<dtype>(arr); | |
} | |
} | |
} | |
#include<cstdio> | |
#include<ctime> | |
#include<cstdint> | |
#include<cstdlib> | |
const int width = 800; | |
const int height = 600; | |
int main() { | |
std::srand(123141); | |
double* src = (double*)std::malloc(height * width * sizeof(double)); | |
double* dst = (double*)std::malloc(height * width * sizeof(double)); | |
for (int i = 0; i < (height * width); i++) { | |
src[i] = ((double)(std::rand() % 1000)) / 1000; | |
} | |
auto t1 = std::clock(); | |
// for (int i=0; i<100; i++) | |
median_filter(dst, src, height, width); | |
auto t2 = std::clock(); | |
std::printf("time: %f\n", double(t2-t1) / CLOCKS_PER_SEC); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment