1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
6 Centre for Digital Music, Queen Mary, University of London.
7 This file Copyright 2010 Chris Cannam.
9 This program is free software; you can redistribute it and/or
10 modify it under the terms of the GNU General Public License as
11 published by the Free Software Foundation; either version 2 of the
12 License, or (at your option) any later version. See the file
13 COPYING included with this distribution for more information.
16 #ifndef MEDIAN_FILTER_H
17 #define MEDIAN_FILTER_H
29 MedianFilter(int size, float percentile = 50.f) :
32 m_sorted(new T[size]),
33 m_sortend(m_sorted + size - 1) {
34 setPercentile(percentile);
43 void setPercentile(float p) {
44 m_index = int((m_size * p) / 100.f);
45 if (m_index >= m_size) m_index = m_size-1;
46 if (m_index < 0) m_index = 0;
51 std::cerr << "WARNING: MedianFilter::push: attempt to push NaN, pushing zero instead" << std::endl;
52 // we do need to push something, to maintain the filter length
56 const int sz1 = m_size-1;
57 for (int i = 0; i < sz1; ++i) m_frame[i] = m_frame[i+1];
58 m_frame[m_size-1] = value;
63 return m_sorted[m_index];
70 T getAt(float percentile) {
71 int ix = int((m_size * percentile) / 100.f);
72 if (ix >= m_size) ix = m_size-1;
78 for (int i = 0; i < m_size; ++i) m_frame[i] = 0;
79 for (int i = 0; i < m_size; ++i) m_sorted[i] = 0;
82 static std::vector<T> filter(int size, const std::vector<T> &in) {
84 MedianFilter<T> f(size);
85 for (int i = 0; i < int(in.size()); ++i) {
88 if (i >= size/2) out.push_back(median);
90 while (out.size() < in.size()) {
92 out.push_back(f.get());
105 // precondition: m_sorted contains m_size-1 values, packed at start
106 // postcondition: m_sorted contains m_size values, one of which is value
107 T *point = std::lower_bound(m_sorted, m_sortend, value);
108 const int n = m_sortend - point;
109 for (int i = n; i > 0; --i) point[i] = point[i-1];
114 // precondition: m_sorted contains m_size values, one of which is value
115 // postcondition: m_sorted contains m_size-1 values, packed at start
116 T *point = std::lower_bound(m_sorted, m_sortend + 1, value);
117 if (*point != value) {
118 std::cerr << "WARNING: MedianFilter::drop: *point is " << *point
119 << ", expected " << value << std::endl;
121 const int n = m_sortend - point;
122 for (int i = 0; i < n; ++i) point[i] = point[i+1];
126 MedianFilter(const MedianFilter &); // not provided
127 MedianFilter &operator=(const MedianFilter &); // not provided