[-28] resolve darknet source image format conversion between RGB2YUV and YUV2RGB

This series darknet parse source code, as it relates to the RGB image, YUV, HSV format image.c, we will resolve image.c rgb_to_yuv involved in () function and yuv_to_rgb () function herein.

 

  • RGB format converted to YUV format

\begin{bmatrix}Y \\ U \\ V \end{bmatrix}=\begin{bmatrix}0.299 & 0.587 & 0.114 \\ -0.1678 & -0.3313 & 0.5\\ 0.5 & -0.4187 & -0.0813 \end{bmatrix} \begin{bmatrix}R \\ G \\ B \end{bmatrix}

 The corresponding function is as follows:

void rgb_to_yuv(image im)
{
    assert(im.c == 3);
    int i, j;
    float r, g, b;
    float y, u, v;
    for(j = 0; j < im.h; ++j){
        for(i = 0; i < im.w; ++i){
            r = get_pixel(im, i , j, 0);
            g = get_pixel(im, i , j, 1);
            b = get_pixel(im, i , j, 2);

            y = .299*r + .587*g + .114*b;
            u = -.14713*r + -.28886*g + .436*b;
            v = .615*r + -.51499*g + -.10001*b;

            set_pixel(im, i, j, 0, y);
            set_pixel(im, i, j, 1, u);
            set_pixel(im, i, j, 2, v);
        }
    }
}

 

  • Converted RGB format YUV format

\begin{bmatrix}R \\ G \\ B \end{bmatrix}=\begin{bmatrix}1 & 0 & 1.402 \\ 1 & -0.34414 & -0.71414\\ 1 & 1.1772 & 0 \end{bmatrix} \begin{bmatrix}Y \\ U \\ V \end{bmatrix}

void yuv_to_rgb(image im)
{
    assert(im.c == 3);
    int i, j;
    float r, g, b;
    float y, u, v;
    for(j = 0; j < im.h; ++j){
        for(i = 0; i < im.w; ++i){
            y = get_pixel(im, i , j, 0);
            u = get_pixel(im, i , j, 1);
            v = get_pixel(im, i , j, 2);

            r = y + 1.13983*v;
            g = y + -.39465*u + -.58060*v;
            b = y + 2.03211*u;

            set_pixel(im, i, j, 0, r);
            set_pixel(im, i, j, 1, g);
            set_pixel(im, i, j, 2, b);
        }
    }
}

[References]

1. https://zhuanlan.zhihu.com/p/75735751

Published 401 original articles · won praise 39 · Views 450,000 +

Guess you like

Origin blog.csdn.net/caicaiatnbu/article/details/104065571