MATLAB Answers

Image read in MATLAB and C

5 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?

  0 Comments

Sign in to comment.

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

Show 2 older comments
Pravitha A
Pravitha A on 25 Feb 2020
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
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.

Sign in to answer this question.


Translated by