Friday, June 17, 2016

YUV to RGB conversion in Javascript

There are many ways to convert YUV (assuming 420P) to RGB in Javascript.

function clamp(n, low, high) {
    if (n < low)  { return(low);  }
    if (n > high) { return(high); }
    return n;
}
 
function yuv2rgb(y, u, v) {
    r = clamp(Math.floor(y+1.4075*(v-128)), 0, 255);
    g = clamp(Math.floor(y-0.3455*(u-128)-(0.7169*(v-128))), 0, 255);
    b = clamp(Math.floor(y+1.7790*(u-128)), 0, 255);
    return({r:r,g:g,b:b});
} 

The clamp function is required since the output result may not be comprised in the [0-255] range.
This is assuming that YUV values are in studio level range (16-235 for Y, 16-240 for U and V).

Note that it is assuming float conversion since Javascript perform all operation with floats
(since it has no notion of integer - unless using asm.js).

More on the meaning of the coefficients and about how to compute them (hopefully) in a later
post.

No comments:

Post a Comment