I have an image (matrix) that has values on 16 bits, that is between 0 and 65535 and I want to write it in a binary file, so I am using fwrite
, as it says in the documentation I have tried to use different precision to write the data on 2 bytes ('integer*2'
, 'uint16'
, etc), but it seems that the data gets saturated on 15 bits, that is the maximum value is 0x7ff, if I use more bytes, let's say 4, the data arrives complete, with values greater than 0x7ff and less than 0xffff. I read in the documentation that fwrite
saturate the values so there will be no Inf or NaN, does that mean that I can write on x bytes, just (x*8 - 1) bits ?!?
Is there any other way to write the image to a bin file with the correct values on 2 bytes ?
Can you run this code and verify it works on your system?
%generate and show data
IM = uint16(((2^16)-1) .* rand(512));
imagesc(IM);axis image;colorbar
%write data
fid=fopen('image.dat','w');
fwrite(fid,IM(:),'uint16');
fclose(fid);
%read data
fid=fopen('image.dat','r');
IM2=fread(fid,inf,'*uint16');
fclose(fid);
IM2=reshape(IM2,512,512);
%check if they are equal
all(IM(:)==IM2(:))
>> 1
If this works, can you check where it differs from your code?