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