Image read in MATLAB and C

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

This 'order' is to check whether the file is big endian supported. So this 'order' value is compared with hex2dec('4949')
if ~(order == hex2dec('4949'))
disp('Error: big endian is not supported');
end
Why this number 4949. Is it applicable to all cases??Because when i tried your code, I got the value '4992'.
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?
function [I idescr] = dng_read(fname)
% open image file
fd = fopen(fname);
% read order
order = fread(fd, 1, 'uint16');
if ~(order == hex2dec('4949'))
disp('Error: big endian is not supported');
end
% skip 2 bytes
fread(fd, 1, 'uint16');
.
.
.
.
This is a funtion to read an image file in dng format. The section where the above mentioned is described directly after the file is read. I don't have any document except the code regarding this. Thanks in advance
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.
like this??
fd=fopen("filename","rb",'ieee-be')

Sign in to comment.

Asked:

on 20 Feb 2020

Commented:

on 25 Feb 2020

Community Treasure Hunt

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

Start Hunting!