core/vil/algo/vil_median.h
Go to the documentation of this file.
00001 #ifndef vil_median_h_
00002 #define vil_median_h_
00003 //:
00004 // \file
00005 // \brief Perform median filtering on images
00006 // \author Tim Cootes
00007 
00008 #include <vil/algo/vil_structuring_element.h>
00009 #include <vil/vil_image_view.h>
00010 #include <vcl_algorithm.h>
00011 
00012 //: Return r-th sorted value of im[offset[k]]
00013 //  Values im[offset[k]] placed into values[k] then sorted. \a values
00014 //  should be a random access iterator into a container of T such
00015 //  that the range [values,values+n) is valid.
00016 template <class T, class Iter>
00017 inline T vil_sorted_value(const T* im, const vcl_ptrdiff_t* offset, Iter values,
00018                           unsigned n, unsigned r)
00019 {
00020   Iter v = values;
00021   for (unsigned i=0;i<n;++i,++v) *v=im[offset[i]];
00022   vcl_nth_element(values, values+r, values+n);
00023   return values[r];
00024 }
00025 
00026 //: Return (n*r)-th sorted value of pixels under element centred at (i0,j0)
00027 // \param r in [0,1].
00028 // \param values used to store values sampled from image before sorting
00029 // Checks boundary overlap
00030 // \relatesalso vil_image_view
00031 // \relatesalso vil_structuring_element
00032 template <class T>
00033 inline T vil_sorted_value(const vil_image_view<T>& image, unsigned plane,
00034                           const vil_structuring_element& element, int i0, int j0,
00035                           vcl_vector<T>& values, double r)
00036 {
00037   values.clear();
00038   vcl_size_t n = element.p_i().size();
00039   for (vcl_size_t k=0;k<n;++k)
00040   {
00041     unsigned int i = i0+element.p_i()[k];
00042     unsigned int j = j0+element.p_j()[k];
00043     if (i<image.ni() && j<image.nj())
00044       values.push_back(image(i,j,plane));
00045   }
00046   vcl_nth_element(values.begin(),values.begin()+vcl_size_t(r*(values.size()-1)),
00047     values.end());
00048   return values[vcl_size_t(r*(values.size()-1))];
00049 }
00050 
00051 //: Computes median value of pixels under structuring element.
00052 // dest_image(i0,j0) is the median value of the pixels under the
00053 // structuring element when it is centred on src_image(i0,j0)
00054 // \relatesalso vil_image_view
00055 // \relatesalso vil_structuring_element
00056 template <class T>
00057 void vil_median(const vil_image_view<T>& src_image,
00058                 vil_image_view<T>& dest_image,
00059                 const vil_structuring_element& element);
00060 
00061 #endif // vil_median_h_