Convert RAW File (images) to PNG

35 views (last 30 days)
rezvan raz
rezvan raz on 11 Aug 2022
Commented: Cris LaPierre on 12 Aug 2022
Hi.
I have a MRI dataset file contain raw and mhd files.
i read this images with the below code :
id = fopen('filename.raw');
img = fread(id,'short');
imgsize = size(img);
rows = 512;
clos =512;
nums = imgsize(1)/rows/clos;
img = reshape(img,[rows,clos,nums]);
single_image = reshape(img(:,:,3),[rows,clos]);
single_show = uint8(single_image);
imshow(single_show)
But in the following I want to convert these images into PNG format.
I would be grateful if you could help me with this image conversion section.
  3 Comments
Cris LaPierre
Cris LaPierre on 12 Aug 2022
I know, but they are essentially the same question, so anyone answering this one could probably help answer the other one.

Sign in to comment.

Answers (1)

DGM
DGM on 12 Aug 2022
Edited: DGM on 12 Aug 2022
A .raw file can be a number of different things. I'm not familiar with .mhd files, so I can't comment on that. It's not clear to us what you have or whether the code you show is working as intended.
If the above code isn't correctly working, you'll have to describe the issue and provide an example file.
If the code is working and single_show is correctly scaled for its class and displaying as expected, then I don't see why you can't just write the image using imwrite(). If you need to write all pages as individual images, just write them in a loop.
fid = fopen('filename.raw');
framestack = fread(id,'short');
fclose(fid);
imgsize = size(framestack);
rows = 512;
clos = 512;
fextension = '.png';
numframes = imgsize(1)/rows/clos;
framestack = reshape(framestack,[rows,clos,nums]);
% loop through frames/pages
for f = 1:numframes
% casting as uint8 may not be necessary or appropriate
% i can't know what your data range/class are
thisframe = uint8(framestack(:,:,f));
% write the frame
new_filename = sprintf('myimage_frame_%03d%s',f,fextension);
imwrite(thisframe,new_filename);
end
If not that, you'll have to clarify.

Community Treasure Hunt

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

Start Hunting!

Translated by