# Color saturation enhancement and Y’CbCr to RGB conversion

Before finishing the contrast enhancement started in previous post, we need to add a Y’CbCr to RGB function. It will allow us to close the loop : RGB=>Y’CbCr=>contrast enhancement on Y’=>RGB. One easy modification we can do while in Y’CbCr domain is modifying color saturation by multiplying Cb and Cr by a common gain. Finally, we will add a user control for this color saturation modification.

We previously used these JFIF formulas to convert image from RGB to Y’CbCr :

```Y' = 0.299 R' + 0.587 G' + 0.114 B'
Cb = - 0.1687 R' - 0.3313 G' + 0.5 B' + 128
Cr = 0.5 R' - 0.4187 G' - 0.0813 B' + 128```

We will now use the JFIF reverse formulas to go back to RGB:

```R = Y + 1.402 (Cr-128)
G = Y - 0.34414 (Cb-128) - 0.71414 (Cr-128)
B = Y + 1.772 (Cb-128)```

While in Y’CbCr domain, we can change color saturation by applying a common gain on Cb ad Cr channels. If we set gain=0, it will turn the image to be in grayscale only. If gain is below 1 the colors will be attenuated, color saturation will be lower. If gain is above 1, the colors will be enhanced.

This is how we do this for this tutorial :

```float y = YCbCr[loc];
float cb = constrain( (sat * (YCbCr[loc]-128)+128), 0, 255);
float cr = constrain( (sat * (YCbCr[loc]-128)+128), 0, 255);

float r = constrain( (y + 1.402 * (cr - 128)), 0, 255);
float g = constrain( (y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128)), 0, 255);
float b = constrain( (y + 1.772 * (cb - 128)), 0, 255);```

As you can see, I also used constrain(), to be sure Cb/Cr and final RGB stay in the [0-255] range.

To improve over the previous tutorials and show that this image processing is really running in Javascript, by your browser, I added a control. There is no built-in user controls in Processing or Processing.js, but there are some examples on the Processing website. I used a slider control from this page.

Now let’s see the final results.

Sketch is available at this location. Source is available here. Play with the slider (yes it is the ugly black box right in the middle of the sketch), upper picture is the reference, down picture will display the effect of the color saturation adjustment, done in Y’CbCr domain.

References:

Tags: , , ,