MATLAB Answers

Writing 3D array to BMP file

4 views (last 30 days)
JSC on 26 Jul 2021
Commented: JSC on 27 Jul 2021
I have a data structure which contains a 3D array (852x512x16) of MRI image data. I need to export this image as a .bmp file. I tried doing this with the save() function (commented below) which seemed to work, but the 3rd party app (Materialise Mimics) that I need to use to process the image said the file type was not recognized, even though the software is definitely capable of working with bmp files (I've done so with other files). To verify that the issue was the file and not the program I tried viewing the bmp in ImageJ and was thrown an error: "java.lang.ArithmeticException: / by zero".
I then tried using the imwrite() function instead but received an error.
clear; clc; close all;
load('PatientImages_1_T2.mat') % load data structure
img=(PatientImages.originalimage(:,:,:)); % extract all 16 slices from struct
% img is now an 852 x 512 x 16 array
%save('patient1_t2.bmp','img'); % file not recognized by Mimics
Error message:
"Error using writebmp (line 27)
Invalid dimensions for X.
Error in imwrite (line 566)
feval(fmt_s.write, data, map, filename, paramPairs{:});
Error in struct2bmp (line 7)
I'm assuming from the error message that the problem is that my image has multiple slices and is a z-stack. Do I need to do some kind of operation slice by slice and then collate them together in one bmp at the end somehow?

Accepted Answer

DGM on 26 Jul 2021
Edited: DGM on 26 Jul 2021
imwrite() doesn't support multipage/multiframe BMP files, because (as far as I know), the format specification for BMP doesn't allow such a thing to exist. If I'm wrong about that, feel free to correct me.
If you must use BMP, multipage/multiframe data would be written to a set of single-page files (possibly organized by directory or filename prefix). Otherwise, just use a TIFF container or something that can support such data.
imwrite(imgstack(:,:,1),'multipage.tif') % write the first image
imwrite(imgstack(:,:,2),'multipage.tif','writemode','append') % append the second image
readbackimgstack = cat(3,imread('multipage.tif',1),imread('multipage.tif',2)); % read back both and concatenate
Compared to BMP, TIFF is generally more flexible and offers other useful options (e.g. lossless compression). If you're worried about general portability of the file, bear in mind that most browsers/viewers don't support mutiframe images in any format other than GIF anyway -- and no, that's not a recommendation to use GIF. Whatever format you use for arbitrary volumetric data likely won't be widely compatible with casual image viewers.
JSC on 27 Jul 2021
Good to know, thanks!

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!