MATLAB Answers


Read image and save it using imwrite?

Asked by Teemu
on 14 Mar 2013

Hello! I read pictures using imread and then try to write it to folder c:\result. The name of the images should be same than readed image, but I like to add index and remove part of the name. So I read image image00123_big.bmp and I like to save image to name image00123_small_'index_number'.bmp. How can I do that?



No products are associated with this question.

2 Answers

Answer by ChristianW
on 14 Mar 2013
 Accepted answer

Input_folder = '.\'; % folder with big images
Output_folder = 'c:\result';
D = dir([Input_folder 'image*_big.bmp']);
Inputs = {}';
Outputs = Inputs; % preallocate
for k = 1:length(Inputs)
    X = imread([Input_folder Inputs{k}]);
    idx = k; % index number
    Outputs{k} = regexprep(Outputs{k}, 'big', ['small_' num2str(idx)]);
    imwrite(X, [Output_folder Outputs{k}],'bmp')


Answer by Alessandro
on 14 Mar 2013
Edited by Alessandro
on 15 Mar 2013

id = 5;
folder = 'c:\result\'
newimagename = [folder 'image00123_small_' num2str(id) '.bmp'];


strid = regexp(readimagename,'\d','match')
id = str2num(strid(1));
folder = 'c:\result\'
newimagename = [folder 'image00123_small_' num2str(id) '.bmp'];

Do not shadow the important Matlab function path by a local variable. This can leed to very strange effects e.g. during debugging.

Use "folder" instead of "path" for a variable name. Don't use "dir" either - it's a built in function.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!