How to save separate '.mat' files with the image name including it ?

I am creating the data base for the Microscopic cell 400 images that extracts the alive and dead cells by calling gerect func. I need to save the result in the .mat files starting with image name.I am using 'try' and 'catch' to generate the database. my code as follows:
[fname path]=uigetfile('.jpg','open a cell pic');
fname=strcat(path,fname);
a=imread(fname);
im=rgb2gray(a);
imshow(im);
title('input image');
while(1)
rect=datapoints(im); % calling getrect function to extract points
%c=input('enter the label: \n');
try
load data
trainSets=[rect c];
data=[data; trainSets];
save data.mat data;
catch
data=[rect c];
save data.mat data
end
this program creating only one .mat File name named as 'data.mat' , but i need .mat for each image i open.as image1.mat, then image2.mat and so on Plz help !!!!!!

1 Comment

You need use the function version of save, rather than the command form, and create a new filename each time you call the function. I would recommend that you use fullfile to create the full filename.

Sign in to comment.

 Accepted Answer

I am using 'try' and 'catch' to generate the database.
Although this works, it is cleaner to check for the existence of the file:
if exist('data.mat', 'file')
FileData = load('data.mat');
trainSets = [FileData.rect, FileData.c];
data = [data; trainSets];
else
data = [rect c];
save('data.mat', 'data');
end
If you want to modify the file name, see: FAQ: Process a sequence of files.
Folder = cd;
for k = 1:10
File = fullfile(Folder, sprintf('image%d.mat', k))
FileData = load(File);
...
end
The same works for
save(File, 'data')

3 Comments

Thanks for the answer, but i am not getting your point. where to put these code lines in my code? Please help
if exist('data.mat', 'file')
FileData = load('data.mat');
trainSets = [FileData.rect, FileData.c];
data = [data; trainSets];
else
data = [rect c];
save('data.mat', 'data');
end
TRY/CATCH is useful to catch errors, but it is more elegant to avoid errors instead. Instead of:
try
load data
...
catch
data = ...
end
you can check the existence of the file at first. If the file is missing, you can create the data without letting Matlab fail in load(). Remember that "load data" imports "data.mat" if it stored anywhere in the Matlab path or in the current folder.

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!