Search code examples
octavecolor-space

Linearly convert color space of RGB image in Octave


I have a 3x3 matrix used to linearly transform RGB colors. How can I convert the color space of an RGB image using that matrix? Should I loop through all the pixels and convert them one by one or does a faster way exist?


Solution

  • Assuming that your 3x3 matrix M is supposed to be multiplied with your pixel value p as follows:

    new_p = M * p;
    

    (with p a column vector), then you can transform your nxmx3 image matrix as follows:

    m = 1920;
    n = 1080; 
    img = rand(n, m, 3);
    tmp = reshape(img, [], 3); % no copy made
    tmp = tmp * M.';
    new_img = reshape(tmp, n, m, 3);
    

    Note that here we transformed M * p into p.' * M.', so that we don't need to transpose the image, which would require copying all its data to a new array. Transposing M is a lot cheaper than transposing tmp.

    You can do the above in a single line, avoiding the need for the tmp array:

    new_img = reshape(reshape(img, [], 3) * M.', n, m, 3);