MATLAB: How to convert indexed image to rgb and back without losing data

Image Processing Toolboxind2rgbrgb2indsteganography

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: http://postimg.org/image/3n2k7067x/
[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?

Best Answer

Your map contains the color [0,0,0] twice. rgb2ind cannot repoduce the same image, because the first appearence of the black color is used. There is no chance to reproduce the original values reliable, if the colormap is not unique.
[J, map] = imread('expert.gif');
disp(map)
% Create a unique map:
[uniqMap, indMap, indUniqMapD] = unique(map, 'rows');
indUniqMap = uint8(indUniqMapD);
uniqJ = indUniqMap(J + 1) - 1;
imwrite(uniqJ, uniqMap, 'expertUniq.gif');
[J, map] = imread('expertUniq.gif');
Jrgb = ind2rgb(J, map);
Jind = rgb2ind(Jrgb, map);
isequal(J, Jind)
Now the conversion works. But the transparent pixels are all black in the image. So the problem was, that the GIF contains transparent pixels, which are not treated as expected by your ind2rgb -> rgb2ind conversion. How could they?