I would use the MPS Median, but my median filter is slightly different - non-zero median. I have tested the implementation below with C++ compiler on the CPU and it works fine; however, I keep getting Compiler failed with XPC_ERROR_CONNECTION_INTERRUPTED error in Metal. I greatly appreciate any tip/suggestion to fix the issus.
template <typename T, size_t N>
inline T median_filter(const T vector[N], const bool is_non_zero = false) {
// I am aware of the ineffiency of the array's copy
T _vector[N]; _vector[0] = vector[0];
for (size_t i = 0; i < N; i++) {
size_t lowest = i;
for (size_t j = i + 1; j < N; j++) {
if (i == 0) _vector[j] = vector[j];
if (_vector[j] < _vector[lowest]) lowest = j;
};
if (i != lowest) {
const T temp = _vector[lowest];
_vector[lowest] = _vector[i];
_vector[i] = temp;
};
};
return count % 2 == 0 ? ((_vector[N/2 - 1] + _vector[N/2]) / 2) : _vector[N/2];
};
Best,