Search code examples
matlabimage-processingrgbsteganographyindexed-image

Convert and indexed image to RGB and back without losing data


I am having trouble converting an indexed image to RGB and then back from RGB to an indexed image. For some reason, the result is different from the original. I am doing steganography so it can't work if the data is changed.

This is my code and this is the sample image:

enter image description here

[J map]=imread('expert.gif');
Jrgb=ind2rgb(J,map);
Jind=rgb2ind(Jrgb,map);
isequal(J,Jind)

Variables J and Jind are supposed to be equal. Why are they being detected as being different?


Solution

  • First of all, I'm certain that this is related to this question.

    The issue is happening because if you actually look at the colormap of your loaded image:

    map = 
           0         0         0
      0.6275    0.3216    0.1765
      0.4902    0.4902    0.4902
      0.8039    0.5216    0.2471
      0.7451    0.7451    0.7451
      0.8627    0.8627    0.8627
      0.9020    0.9020    0.9804
           0         0         0
    

    You'll see that the color black (0,0,0) actually exists in there twice so both index = 0 and index = 7 will resolve to black in the RGB image.

    When you do the conversion back to an indexed image, MATLAB is going to use the same index for both of those (because they are obviously the same color) even if the colormap that you pass to rgb2ind is the same colormap.

    That explains why the differences that you're seeing are where the transparent pixels are (around the periphery).

    enter image description here

    As far as dealing with this, I think it's a little tricky. Unfortunately the transparency (3rd output) output of imread is an empty array.

    You could potentially change the input colormap so that the first and last rows aren't the same (set the last row to 1's) and then you should get back something comparable.

    map(end,:) = 1;
    rgb = ind2rgb(J, map);
    ind = rgb2ind(rgb, map);
    isequal(J, ind);
    

    In general, due to MATLAB's limitations, GIFs with transparency may not be the best test case for playing with stenography.