]> Creatis software - cpPlugins.git/blob - lib/cpExtensions/Algorithms/RGBToHSVFunction.h
...
[cpPlugins.git] / lib / cpExtensions / Algorithms / RGBToHSVFunction.h
1 // -------------------------------------------------------------------------
2 // @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)
3 // -------------------------------------------------------------------------
4
5 #ifndef __CPEXTENSIONS__ALGORITHMS__RGBTOHSVFUNCTION__H__
6 #define __CPEXTENSIONS__ALGORITHMS__RGBTOHSVFUNCTION__H__
7
8 #include <cmath>
9 #include <limits>
10 #include <vnl/vnl_math.h>
11
12 #include <itkRGBPixel.h>
13
14 namespace cpExtensions
15 {
16   namespace Algorithms
17   {
18     /**
19      */
20     template< class P >
21     struct RGBToHSVFunction
22     {
23       typedef RGBToHSVFunction      Self;
24       typedef P                     TOutPixel;
25       typedef typename P::ValueType TValue;
26
27       template< class Tr, class Tg, class Tb >
28       P operator()( const Tr& r, const Tg& g, const Tb& b ) const
29         {
30           static const double mVal =
31             double( std::numeric_limits< TValue >::max( ) );
32           static const double _0 = double( 0 );
33           static const double _1 = double( 1 );
34           static const double _2 = double( 2 );
35           static const double _3 = double( 3 );
36           static const double _2pi = _2 * double( vnl_math::pi );
37
38           P hsv;
39
40           double R = double( r );
41           double G = double( g );
42           double B = double( b );
43           double sRGB = R + G + B;
44           double RG = R - G;
45           double RB = R - B;
46           double GB = G - B;
47
48           // Hue
49           double A = std::sqrt( ( RG * RG ) + ( RB * GB ) );
50           if( A != _0 )
51             A = std::acos( ( RG + RB ) / ( _2 * A ) );
52           A /= _2pi;
53           hsv[ 0 ] = TValue( mVal * ( ( G >= B )? A: _1 - A ) );
54
55           // Saturation
56           if( sRGB != _0 )
57           {
58             double C = ( G < R )? G: R;
59             C        = ( B < C )? B: C;
60             hsv[ 1 ] = TValue( mVal * ( _1 - ( ( _3 * C ) / sRGB ) ) );
61           }
62           else
63             hsv[ 1 ] = TValue( 0 );
64
65           // Value
66           hsv[ 2 ] = TValue( sRGB / _3 );
67           return( hsv );
68         }
69
70       template< class C >
71       TOutPixel operator()( const itk::RGBPixel< C >& rgb ) const
72         {
73           return(
74             this->operator()(
75               rgb.GetRed( ), rgb.GetGreen( ), rgb.GetBlue( )
76               )
77             );
78         }
79     };
80
81   } // ecapseman
82
83 } // ecapseman
84
85 #endif // __CPEXTENSIONS__ALGORITHMS__RGBTOHSVFUNCTION__H__
86
87 // eof - $RCSfile$