MATLAB: Decreasing range of values

castmatrix assignmentrounding error

I have a 64 x 64 x 7 dimension matrix representing seven grey scale value (0-255) images. I want to modify the range of these values from 0 – 255 to -1 – 1 and vice versa based on a flag passed, with values approaching but not reaching -1 and 1. For reasons unknown when I perform the proper operation the values are all only 0 or 1. The 7 64 x 64 2d matrices in the 3d matrix are a result of passing a .tif to the imread() function. I can include that code if needed. I don't know if the values are being rounded at some point. Any help is appreciated.
function convertedImages = convert_greyscale(Images, flag)
% If the flag is 0, convert from 0 - 255 to -1 - 1
if flag == 0
for i = 1 : size(Images, 1)
for j = 1 : size(Images, 2)
for k = 1 : size(Images, 3)
Images(i, j, k) = Images(i, j, k) / 255 * 2 - .999;
end
end
end
% Else convert from -1 - 1 to 0 - 255
else
for i = 1 : size(Images, 1)
for j = 1 : size(Images, 2)
for k = 1 : size(Images, 3)
Images(i, j, k) = floor((Images(i, j, k) + 1) / (2 / 255));
end
end
end
end
convertedImages = Images;
end

Best Answer

You have
Images(i, j, k) = Images(i, j, k) / 255 * 2 - .999;
but you are passing in uint8, and the result of operations on uint8 is always uint8.
Related Question