Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Desaturate a Color?

I might not be using the correct color terminology but I want to basically be able to scale colors similar to the picture attached. I have been searching for saturation to do this, as it appears the right version is just a must less saturated version of the left.

enter image description here

I was trying this (which I found) but it is not looking correct at all:

Public Shared Function GetDesaturatedColor(color As Color) As Color
    Const kValue As Double = 0.01R

    Dim greyLevel = (color.R * 0.299R) + _
                    (color.G * 0.587R) + _
                    (color.B * 0.144R)

    Dim r = greyLevel * kValue + (color.R) * (1 - kValue)
    Dim g = greyLevel * kValue + (color.G) * (1 - kValue)
    Dim b = greyLevel * kValue + (color.B) * (1 - kValue)

    ' ColorUtils.ToByte converts the double value 
    ' to a byte safely
    Return color.FromArgb(255, _
                          ColorUtils.ToByte(r), _
                          ColorUtils.ToByte(g), _
                          ColorUtils.ToByte(b))
End Function

Does anyone know of some algorithm that can do this?

like image 541
test Avatar asked Nov 11 '12 02:11

test


2 Answers

For those that want to avoid converting everything to HSL/HSV and back, this works reasonably well (if not correctly depending on what one thinks the "correct" desaturated image is):

f = 0.2; // desaturate by 20%
L = 0.3*r + 0.6*g + 0.1*b;
new_r = r + f * (L - r);
new_g = g + f * (L - g);
new_b = b + f * (L - b);

This is converting r,g,b to grayscale using the common assumption that green, red and blue correspond to the Luma of an image decreasing proportions respectively. So L is a grayscale image and then f is just linearly interpolating between the input RGB image and that grayscale image.

like image 104
Alec Jacobson Avatar answered Sep 30 '22 05:09

Alec Jacobson


As @Brad mentioned in the comments to your post, your first step is to convert the colours from RGB to either HSL or HSV. From there, reducing the saturation is trivial - just subtract or divide the saturation by a value to reduce it.

After that, convert your HSL/HSV color back into RGB and it's ready for use.

How to change RGB color to HSV? has a good example of how to do this, as does Manipulating colors in .net.

like image 42
Fabian Tamp Avatar answered Sep 30 '22 05:09

Fabian Tamp