Get HSB-mode saturation of a color constructed in RGB

If I set colorMode(RGB) and create a color c, then get saturation(c), it always gives me the HSL-mode saturation number, which is different from the HSB-mode number. I can’t think of any way to get the HSB-mode saturation of an RGB color. I know the algorithm to do it, so I could write my own function, but if someone doesn’t know that, it doesn’t seem possible. Is there no function that can convert a color from any mode to any other mode?

If you want a different color model than HSB then you’ll need to implement it yourself. Here’s an old guide on the difference between HSL and HSB.

Also, here is a snippet I adapted from a StackOverflow answer for use in one of my sketches:

// The built in p5.js RGB -> lightness function leaves something to be desired.
// Credit: https://stackoverflow.com/a/13558570/229247

// sRGB luminance(Y) values
const rY = 0.212655;
const gY = 0.715158;
const bY = 0.072187;

// Inverse of sRGB "gamma" function. (approx 2.2)
function inv_gam_sRGB(ic) {
    const 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)
function gam_sRGB(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);
}

// GRAY VALUE ("brightness")
function gray(c) {
    return gam_sRGB(
            rY*inv_gam_sRGB(red(c)) +
            gY*inv_gam_sRGB(green(c)) +
            bY*inv_gam_sRGB(blue(c))
    );
}
2 Likes

If you want a different color model than HSB then you’ll need to implement it yourself.

I’m not saying I want a different HSB, I’m just saying I want a way to get HSB’s S from a color that was constructed in RGB. The problem is that saturation() returns HSL’s S unless the color was made in HSB, but if I have a color that was made in RGB, I can’t convert it.

Hello,

A related topic:

:)

I may have misread what you were looking for. Answer: No there is no such function. You have to write your own function.

Hi @modusponens,

This seems to work:

Setup:

colorMode(RGB);
c = color( 'rgb(20,110,40)' ); // or similar so you have a color with mode = "rgb"

Hacky gets:

colorMode(HSB);
saturation( color( c.toString() ) );  // returns 81.81818181818183

colorMode(HSL);
saturation( color( c.toString() ) ); // returns 69.23076923076924

Hacky 2:

colorMode(RGB);
c = color( 'rgb(20,110,40)' );

c.mode = HSL;
saturation(c); // 69.23076923076924

c.mode = RGB;  // lets just put that back where we found it

Method 2 involves mutating the color back and forth. bad idea? I dunno

1 Like

Method 2 involves mutating the color back and forth. bad idea? I dunno

Hmm, I didn’t even know you could do that! This might actually be a good idea, depending on what I was trying to do, which, to be honest, I have now forgotten.