vil_math.cxx
Go to the documentation of this file.
1 // This is core/vil/vil_math.cxx
2 #include <iostream>
3 #include <cstdlib>
4 #include "vil_math.h"
5 //:
6 // \file
7 // \author Amitha Perera.
8 //
9 // \verbatim
10 // Modifications
11 // \endverbatim
12 
13 #ifdef _MSC_VER
14 # include <vcl_msvc_warnings.h>
15 #endif
16 
18 {
19  std::cerr << "vil_math_median is currently not implemented for this data type\n";
20  std::abort();
21 }
22 
23 template <>
24 void vil_math_median(vxl_byte& median, const vil_image_view<vxl_byte>& im, unsigned p)
25 {
26  unsigned ni = im.ni();
27  unsigned nj = im.nj();
28 
29  // special case the empty image.
30  if ( ni*nj == 0 ) {
31  median = 0;
32  return;
33  }
34 
35  unsigned hist[256] = { 0 };
36  for (unsigned j=0;j<nj;++j) {
37  for (unsigned i=0;i<ni;++i) {
38  ++hist[ im(i,j,p) ];
39  }
40  }
41 
42  unsigned tot = ni*nj;
43  // Target is ceil(tot/2)
44  unsigned tgt = (tot+1) / 2;
45  unsigned cnt = 0;
46  unsigned idx = 0;
47  while ( cnt < tgt ) {
48  cnt += hist[idx];
49  ++idx;
50  }
51 
52  // Test for halfway case
53  if ( cnt == tgt && tot % 2 == 0 ) {
54  // idx is
55  unsigned lo = idx-1;
56  while ( hist[idx] == 0 ) {
57  ++idx;
58  }
59  median = vxl_byte((lo+idx)/2);
60  }
61  else {
62  median = vxl_byte(idx-1);
63  }
64 }
Various mathematical manipulations of 2D images.
Concrete view of image data of type T held in memory.
Definition: vil_fwd.h:13
unsigned ni() const
Width.
unsigned nj() const
Height.
void vil_math_median(imT &median, const vil_image_view< imT > &im, unsigned p)
Median of elements in plane p of an image.
Definition: vil_math.h:282
void vil_math_median_unimplemented()
Definition: vil_math.cxx:17