Search code examples
c++graphicsrgbhsl

Converting RGB to HSL in C++


Currently trying to convert RGB to HSL. Can't figure out where I'm going wrong but my H & S values shows as 0 which is the problem. Here is what I have:

#include <iostream>
#include <cstdlib>
#include <cmath>
float Min( float fR, float fG, float fB )
{
    float fMin = fR;
    if (fG < fMin)
    {
        fMin = fG;
    }
    if (fB < fMin)
    {
        fMin = fB;
    }
    return fMin;
}


float Max( float fR, float fG, float fB)
{
    float fMax = fR;
    if (fG > fMax)
    {
        fMax = fG;
    }
    if (fB > fMax)
    {
        fMax = fB;
    }
    return fMax;
}

void RGBToHSL( int R, int G, int B, int& H, int& S, int& L )
{
    int r = 100.0;
    int g = 100.0;
    int b = 200.0;

    float fR = r / 255.0;
    float fG = g / 255.0;
    float fB = b / 255.0;


    float fCMin = Min(fR, fG, fB);
    float fCMax = Max(fR, fG, fB);


    L = 50 * (fCMin + fCMax);

    if (fCMin = fCMax)
    {
        S = 0;
        H = 0;
        return;

    }
    else if (L < 50)
    {
        S = 100 * (fCMax - fCMin) / (fCMax + fCMin);
    }
    else
    {
        S = 100 * (fCMax - fCMin) / (2.0 - fCMax - fCMin);
    }

    if (fCMax == fR)
    {
        H = 60 * (fG - fB) / (fCMax - fCMin);
    }
    if (fCMax == fG)
    {
        H = 60 * (fB - fR) / (fCMax - fCMin) + 120;
    }
    if (fCMax == fB)
    {
        H = 60 * (fR - fG) / (fCMax - fCMin) + 240;
    }
    if (H < 0)
    {
        H = H + 360;
    }
}

Lightness value is 58 which is fine but I'm expecting to see a value of 240 for Hue and 47 for Saturation.

Any help would be highly appreciated.

Thanks.


Solution

  • if (fCMin = fCMax)

    should be

    if (fCMin == fCMax)