Image read in MATLAB and C

3 views (last 30 days)
Pravitha A
Pravitha A on 20 Feb 2020
Commented: Pravitha A on 25 Feb 2020
I have program to read an image in MATLAB
% open image file
fd = fopen("i00.dng");
% read order
order = fread(fd, 1, 'uint16');
I converted this to C as follows:
int order[1234];
FILE *fd=fopen("i00.dng","wb");
fread(order,2,1,fd);
printf("%d",order);
But the value of order in both cases is different. Did I convert it wrong?What is the exact replica of this code in C?

Answers (1)

James Tursa
James Tursa on 20 Feb 2020
Edited: James Tursa on 20 Feb 2020
An int is likely 4 bytes on your machine, not 2 bytes. Also the expression "order" by itself evaluates as a pointer to the first element, not the first element itself. And you should be opening the file for reading, not writing. So,
unsigned short order[1234];
FILE *fd = fopen("i00.dng","rb"); /* you should check that this result is not NULL */
fread(order,2,1,fd);
printf("%u\n",order[0]);
This is almost a replica of the MATLAB code. Your MATLAB code converts the input to double. If you don't want that, then use an asterisk on the class name:
order = fread(fd, 1, '*uint16');
  5 Comments
Walter Roberson
Walter Roberson on 25 Feb 2020
If you want big endian then you need to pass in the third parameter to fopen as 'b' or 'ieee-be'. Or you can instead pass that information as the fifth parameter to fread(). Or you can swapbytes() the value that you fread.
Pravitha A
Pravitha A on 25 Feb 2020
like this??
fd=fopen("filename","rb",'ieee-be')

Sign in to comment.

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!