MATLAB: How to convert all jpg images to gray and then save them in different file

.jpgfor loopgrayImage Processing Toolboxloopmatrgb

I have a set of images(jpg) in a file and I want to create a for loop to go through all of them and convert them to a gray scale images and save them into the same directory. I am using this code:
contents = dir('*.jpg') % or whatever the filename extension is
for i = 1:numel(contents)
filename = contents(i).name;
% Open the file specified in filename, do your processing...
[path name] = rgb2gray(filename);
out_filename = sprintf('%s.jpg', name);
% write jpg output to 'out_filename'
fprintf(1, 'Writing %s\n', out_filename);
end
I actually want to know how I can do two things. First is gray all the images and store them into my directory, second is to add my gray images into .mat file I will appreciate your help.

Best Answer

iris - according to rgb2gray you would first need to read in the image, then convert it to grayscale, and then write it to file. You cannot (unless supported in other versions) read and convert the file directly using rgb2gray as
[path name] = rgb2gray(filename);
Try the following instead
contents = dir('*.jpg') % or whatever the filename extension is
for k = 1:numel(contents)
filename = contents(k).name;
rgbImg = imread(filename);
gsImg = rgb2gray(rgbImg);
[~,name,~] = fileparts(filename);
gsFilename = sprintf('%s_gs.jpg', name);
imwrite(gsImg,gsFilename);
end
We use the fileparts to extract the name of the file only (so not the path nor the extension) so that we can suffix it with a _gs to distinguish it form the RGB image file.
As for saving to a mat file, see save for details.