Go to the documentation of this file.00001
00002 #include "vil_math.h"
00003
00004
00005
00006
00007
00008
00009
00010
00011 #include <vcl_iostream.h>
00012 #include <vcl_cstdlib.h>
00013
00014 void vil_math_median_unimplemented()
00015 {
00016 vcl_cerr << "vil_math_median is currently not implemented for this data type\n";
00017 vcl_abort();
00018 }
00019
00020 VCL_DEFINE_SPECIALIZATION
00021 void vil_math_median(vxl_byte& median, const vil_image_view<vxl_byte>& im, unsigned p)
00022 {
00023 unsigned ni = im.ni();
00024 unsigned nj = im.nj();
00025
00026
00027 if ( ni*nj == 0 ) {
00028 median = 0;
00029 return;
00030 }
00031
00032 unsigned hist[256] = { 0 };
00033 for (unsigned j=0;j<nj;++j) {
00034 for (unsigned i=0;i<ni;++i) {
00035 ++hist[ im(i,j,p) ];
00036 }
00037 }
00038
00039 unsigned tot = ni*nj;
00040
00041 unsigned tgt = (tot+1) / 2;
00042 unsigned cnt = 0;
00043 unsigned idx = 0;
00044 while ( cnt < tgt ) {
00045 cnt += hist[idx];
00046 ++idx;
00047 }
00048
00049
00050 if ( cnt == tgt && tot % 2 == 0 ) {
00051
00052 unsigned lo = idx-1;
00053 while ( hist[idx] == 0 ) {
00054 ++idx;
00055 }
00056 median = vxl_byte((lo+idx)/2);
00057 }
00058 else {
00059 median = vxl_byte(idx-1);
00060 }
00061 }