Mentions légales du service

Skip to content
Snippets Groups Projects
rgb2ycbcr.m 1.58 KiB
% Author :  Hadi Amirpour 
% email  :  hadi.amirpour@gmail.com
% Copyright(c) EmergIMG,
%              Universidade da Beira Interior

% script for RGB 444 to YCbCr 444 color space conversion in n bits
% Input: 
        % 1-rgb   ---> RGB image in double format
        % 2-n     ---> number of the bits, this number should be either 8 or 10

% Output: 
        % 1-ycbcr ---> YCbCr image in n bits
% Modified by Elian Dib (elian.dib@inria.fr) on October, 18th 2018

function [ycbcr] = rgb2ycbcr(rgb,n,fullRange,conv2int)

%  Recommendation ITU-R BT.709-6
M = [ 0.212600   0.715200  0.072200 ;
     -0.114572  -0.385428  0.500000 ;
      0.500000  -0.454153 -0.045847];
  
if (nargin < 2)
    if isinteger(rgb)
    [~,n] = utils.precision(class(rgb));
    else
        n = 0;
    end
end

if (nargin < 3)
    fullRange = true;
end

if (nargin < 4)
    if isinteger(rgb)
        conv2int = true;
    else
        conv2int = false;
    end
end

rgb = double(rgb)./double(2^n-1);

if fullRange
    offsetY = 0;
    scaleY = 255;
    offsetC = 128;
    scaleC = 255;
else
    offsetY = 16;
    scaleY = 219;    
    offsetC = 128;
    scaleC = 224;
end

ycbcr        = reshape(double(rgb), [], 3) * M';
ycbcr(:,1)   = (scaleY*ycbcr(:,1)   + offsetY)*2^(n-8);
ycbcr(:,2:3) = (scaleC*ycbcr(:,2:3) + offsetC)*2^(n-8);
ycbcr        = reshape(ycbcr, size(rgb));

if conv2int
    if(n<=8)
        ycbcr = uint8(ycbcr);
    elseif (n<=16)
        ycbcr = uint16(ycbcr);
    elseif (n<=32)
        ycbcr = uint32(ycbcr);
    elseif (n<=64)
        ycbcr = uint64(ycbcr);
    else
        print('invalid bit depth')
    end
end
end