]> 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 #include <itkVector.h>
14
15 namespace cpExtensions
16 {
17   namespace Algorithms
18   {
19     /**
20      */
21     template< class O >
22     struct RGBToHSVFunction
23     {
24       typedef RGBToHSVFunction    Self;
25       typedef itk::Vector< O, 3 > TOutPixel;
26
27       template< class Tr, class Tg, class Tb >
28       TOutPixel operator()( const Tr& r, const Tg& g, const Tb& b ) const
29         {
30           static const double mVal =
31             double( std::numeric_limits< O >::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           TOutPixel 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 ] = O( 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 ] = O( mVal * ( _1 - ( ( _3 * C ) / sRGB ) ) );
61           }
62           else
63             hsv[ 1 ] = O( 0 );
64
65           // Value
66           hsv[ 2 ] = O( 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$