Image read in MATLAB and C
Show older comments
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
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
Pravitha A
on 24 Feb 2020
Edited: Pravitha A
on 24 Feb 2020
James Tursa
on 24 Feb 2020
Can you post the exact wording of the doc where it is describing this '4949' number so I know for sure what we are comparing to?
Pravitha A
on 25 Feb 2020
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
on 25 Feb 2020
Categories
Find more on Low-Level File I/O 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!