MATLAB Answers


How to save images as jpgs from .mat files struct

Asked by Mamoona Nisar on 19 Feb 2019
Latest activity Commented on by Mahesh Potdar on 10 Mar 2019
Hi ,I have 3064 .mat files dataset of brain tumors ,Prepareing data with lables for CNN.Each .mat file has struct 1x1 . Struct has following has these information: cjdata.image and cjdata.label.
And image is stored as cjdata.image.
I want to load all the .mat files:
1.mat ,2.mat ,3.mat ........................3064.mat
Want to apply these three opertions on each .mat file iteratively using a loop
1- accessing image from struct
2.convert into gray scale grayscale image as as 1.jpg 2.jpg.....3065.jpg
% Reading folder that has 3064 .mat files
myFolder = 'C:\Users\join2\Desktop\FIGSHARE\figshare data progress\figshare jpg data\3064 images';
filePattern = fullfile(myFolder, '*.mat');
Pgraymap = dir(filePattern);
for I = 1:length(Pgraymap)
baseFileName = Pgraymap(I).name;
str = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', str);
img1 = imread(str); % new
% load .mat
% acessing images from .mat files. each .mat has image as strcture,that
% is "cjdata.image"
% gray scale conversion
% save all d.cjdata.image as jpgs in myFolder .plz help i don't know how to save


Sign in to comment.

2 Answers

Answer by Akira Agata
on 19 Feb 2019
 Accepted Answer

To save matrix as an image, please use imwrite function.
In addition, if you save your data as an image file, I would recommend saving as .tiff or .png to keep data accuracy, because .jpg is a lossy compression method.
The following is a simple example.
inputFolder = 'C:\Users\join2\Desktop\FIGSHARE\figshare data progress\figshare jpg data\3064 images';
outputFolder = pwd; % Please change, if needed.
fileList = dir(fullfile(inputFolder,'*.mat'));
for kk = 1:numel(fileList)
S = load(fullfile(fileList(kk).folder,fileList(kk).name));
I = S.cjdata.image;
I = mat2gray(I);
fileName = replace(fileList(kk).name,'.mat','.tiff');


(Actually using replace or strrep is fragile and I would not recommend doing this: it will replace exactly that substring even if occurs in the middle of the filename. The robust way to write this code would be to use the second output of fileparts).
thankyou so much for your help.
Successfully saved all data as pngs
Hi Mamoona-san,
I'm glad to hear that you successfully saved all data!
By the way, the errors you mentioned here would be due to your MATLAB version.
The field 'folder' for ourput variable of dir function was added in R2016b, and replace function was introduced in R2016b as well. So, if your MATLAB version is R2016a or earlier, these error appears.

Sign in to comment.

Answer by Mamoona Nisar on 19 Feb 2019

thankyou so much for your help. @Akira Agata
Successfully saved all data as jpgs.


Show 1 older comment
open the folder where you have saved the file. @mahesh
@Mamoona Nisar- Will you share your Email Id, Please?

Sign in to comment.