Skip to content

Instantly share code, notes, and snippets.

@twdragon
Forked from aksarben09/rgb2yuv420p.cc
Created April 14, 2018 19:57
Show Gist options
  • Save twdragon/947133931da1450e1998e6f141b77e67 to your computer and use it in GitHub Desktop.
Save twdragon/947133931da1450e1998e6f141b77e67 to your computer and use it in GitHub Desktop.
RGB To YUV420p
void rgb2yuv420p(uint8_t *destination, uint8_t *rgb, size_t width, size_t height)
{
size_t image_size = width * height;
size_t upos = image_size;
size_t vpos = upos + upos / 4;
size_t i = 0;
for( size_t line = 0; line < height; ++line )
{
if( !(line % 2) )
{
for( size_t x = 0; x < width; x += 2 )
{
uint8_t r = rgb[3 * i];
uint8_t g = rgb[3 * i + 1];
uint8_t b = rgb[3 * i + 2];
destination[i++] = ((66*r + 129*g + 25*b) >> 8) + 16;
destination[upos++] = ((-38*r + -74*g + 112*b) >> 8) + 128;
destination[vpos++] = ((112*r + -94*g + -18*b) >> 8) + 128;
r = rgb[3 * i];
g = rgb[3 * i + 1];
b = rgb[3 * i + 2];
destination[i++] = ((66*r + 129*g + 25*b) >> 8) + 16;
}
}
else
{
for( size_t x = 0; x < width; x += 1 )
{
uint8_t r = rgb[3 * i];
uint8_t g = rgb[3 * i + 1];
uint8_t b = rgb[3 * i + 2];
destination[i++] = ((66*r + 129*g + 25*b) >> 8) + 16;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment