Color Space Transform

This sample source code illustrates the use of the transformation between different image color spaces. The sample code is based on Microsoft Visual Basic. The Ilixis Developer's Corner does not warrant that the sample source code. This sample source code is for guidance and illustration purposes only.



' HSL values used are between 0 and 1
' RGB values used are between 0 and 255
' All variables used are of data type DOUBLE


RGB to HSL

TmpR = ( R / 255 )
TmpG = ( G / 255 )
TmpB = ( B / 255 )

' fnMin gives the minimum of the 3 parameters.
' In this case, its the minimum RGB value
TmpMin = fnMin( TmpR, TmpG, TmpB )

' fnMin gives the maximum of the 3 parameters.
' In this case, its the maximum RGB value
TmpMax = fnMax( TmpR, TmpG, TmpB )

' DelMax will be the delta between the Maximum and Minimum values
DelMax = TmpMax - TmpMin

L = ( TmpMax + TmpMin ) / 2

If ( DelMax == 0 ) Then
    ' This is a gray
    H = 0
    S = 0
Else 
    If ( L < 0.5 ) Then
        S = DelMax / ( TmpMax + TmpMin )
    Else
        S = DelMax / ( 2 - DelMax )
    End If
    
    DelR = ( ( ( TmpMax - TmpR ) / 6 ) + ( DelMax / 2 ) ) / DelMax
    DelG = ( ( ( TmpMax - TmpG ) / 6 ) + ( DelMax / 2 ) ) / DelMax
    DelB = ( ( ( TmpMax - TmpB ) / 6 ) + ( DelMax / 2 ) ) / DelMax
    
    If ( TmpR == TmpMax ) Then
        H = DelB - DelG
    ElseIf ( TmpG == TmpMax ) Then
        H = ( 1 / 3 ) + DelR - DelB
    ElseIf ( TmpB == TmpMax ) Then
        H = ( 2 / 3 ) + DelG - DelR
    End If
    
    If ( H < 0 ) Then
        H = H + 1
    End If
    If ( H > 1 ) Then
        H = H - 1
    End If
End If


HSL to RGB


If ( S = 0 ) Then
    R = L * 255
    G = L * 255
    B = L * 255
Else
    If ( L < 0.5 ) Then
        Tmp2 = L * ( 1 + S )
    Else
        Tmp2 = ( L + S ) - ( S * L )
    End If
    
    Tmp1 = 2 * L - Tmp2
    
    R = 255 * fnHtoRGB( Tmp1, Tmp2, H + ( 1 / 3 ) ) 
    G = 255 * fnHtoRGB( Tmp1, Tmp2, H )
    B = 255 * fnHtoRGB( Tmp1, Tmp2, H - ( 1 / 3 ) )
End If
    
    
Private Function fnHtoRGB( v1, v2, v3 )
    
    If ( v3 < 0 ) Then
        v3 = v3 + 1
    End If
    If ( v3 > 1 ) Then
        v3 = v3 - 1
    End If
    
    If ( ( 6 * v3 ) < 1 ) Then
        fnHtoRGB = ( v1 + ( v2 - v1 ) * 6 * v3 )
    ElseIf ( ( 2 * v3 ) < 1 ) Then
        fnHtoRGB = v2
    ElseIf ( ( 3 * v3 ) < 2 ) Then
        fnHtoRGB = ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - v3 ) * 6 )
    Else
        fnHtoRGB = v1
    End If

End Function




 


  Developer's Corner
 
Introduction
Imaging Toolkits
TWAIN
Image Formats
Color Spaces
Auto Recognition
Useful Links
Transform Logic
RGB <-> CMY
CMY <-> CMYK
RGB <-> HSL
Learn More...
Concepts