在C ++中将RGB转换为HSL

时间:2017-12-13 05:12:48

标签: c++ graphics rgb hsl

目前正在尝试将RGB转换为HSL。无法弄清楚我哪里出错了但我的H& S值显示为0,这是问题。 这就是我所拥有的:

#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;
    }
}

亮度值是58,这很好,但我希望Hue的值为240,饱和度的值为47.

任何帮助都将受到高度赞赏。

感谢。

1 个答案:

答案 0 :(得分:2)

if (fCMin = fCMax)

应该是

if (fCMin == fCMax)