Formula to determine brightness of RGB color

前端 未结 20 3469
猫巷女王i
猫巷女王i 2020-11-21 23:16

I\'m looking for some kind of formula or algorithm to determine the brightness of a color given the RGB values. I know it can\'t be as simple as adding the RGB values toget

20条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 23:43

    Below is the only CORRECT algorithm for converting sRGB images, as used in browsers etc., to grayscale.

    It is necessary to apply an inverse of the gamma function for the color space before calculating the inner product. Then you apply the gamma function to the reduced value. Failure to incorporate the gamma function can result in errors of up to 20%.

    For typical computer stuff, the color space is sRGB. The right numbers for sRGB are approx. 0.21, 0.72, 0.07. Gamma for sRGB is a composite function that approximates exponentiation by 1/(2.2). Here is the whole thing in C++.

    // sRGB luminance(Y) values
    const double rY = 0.212655;
    const double gY = 0.715158;
    const double bY = 0.072187;
    
    // Inverse of sRGB "gamma" function. (approx 2.2)
    double inv_gam_sRGB(int ic) {
        double c = ic/255.0;
        if ( c <= 0.04045 )
            return c/12.92;
        else 
            return pow(((c+0.055)/(1.055)),2.4);
    }
    
    // sRGB "gamma" function (approx 2.2)
    int gam_sRGB(double v) {
        if(v<=0.0031308)
            v *= 12.92;
        else 
            v = 1.055*pow(v,1.0/2.4)-0.055;
        return int(v*255+0.5); // This is correct in C++. Other languages may not
                               // require +0.5
    }
    
    // GRAY VALUE ("brightness")
    int gray(int r, int g, int b) {
        return gam_sRGB(
                rY*inv_gam_sRGB(r) +
                gY*inv_gam_sRGB(g) +
                bY*inv_gam_sRGB(b)
        );
    }
    

提交回复
热议问题