So I'm sure this is an incredibly simple question, but I'm having trouble reading and displaying data from a .bin file. Basically, I have an image (256x256, 8 bits per pixel) that I'm trying to read in and display. While I can get this to work for a .jpg or .tif, I can't get it to work for a .bin file. Here's my code as of now:
file = fopen('image.bin', 'r');
A = fread(file);
imshow(A) %not sure if this is correct...
% imshow(file) doesn't work
% imshow('image.bin') doesn't work either
fclose(file);
Any ideas?
I'm going to assume that your .bin
file consists of raw image intensities that are stored in a binary file. Your fread
call will simply read the contents of the file into an array, but you need to be careful. By default, the values will be read in as 64-bit double
values in MATLAB so what will happen is that a single double
value will contain 8 image pixels. As such, what you need to do is modify how the values are being read in with fread
. Specifically, you need to do this:
A = fread(file, 256*256, 'uint8=>uint8');
This is saying that you are going to read a total of 256 x 256 image pixels, where the input binary file stores the data in unsigned 8-bit integers. After, the data is read into MATLAB as the same type. Now, what you need to do next is to reshape
the array so that it becomes a 256 x 256 image.
However, because fread
reads in the data in column-major, each row of this reshaped image would be placed into the columns, and so you need to transpose the reshaped matrix when you're done. Specifically:
A = reshape(A, 256, 256).';
Now, A
would be your 256 x 256 image that you are seeking. You can now show this image with imshow(A);
.