user1769107
user1769107

Reputation: 265

run M-file on multiple images and write output images

I have written a M-file. I'd like to run this M-file on multiple images and then write output .tif images by naming separately. Is there easy way to do this?

Thank all

Upvotes: 0

Views: 2005

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38052

Best practice is to write a function:

function img( inputName, outputName )

    if ~iscell(inputName)
         img( {inputName}, {outputName} ); 
            return; 
    end   

    for ii = 1:numel(inputName)

        im = imread(inputName{ii});

        ...

        [do operations on im]

        ...

        imwrite(im, outputName{ii}, 'tiff');

    end

end

which you can call from a script, class, function or command window like so:

img(...
    {'file1.bmp', 'file2.bmp', ...},...
    {'file1.tif', 'file2.tif', ...}...
);

You can get input filenames like so:

[filename, pathname] = uigetfile( ...
   {'*.bmp','bitmap-files (*.bmp)'; ...
    '*.*',  'All Files (*.*)'}, ...
    'Pick a file', ...
    'MultiSelect', 'on');

so you can use

if filename ~= 0
    img(...
        [char(pathname) char(filename)],
        {'file1.tif', 'file2.tif', ...}...
    );
else
    error('No file selected.');
end

which already indicates you can better recycle the input filenames:

function img( fileNames )

    ... % function's mostly the same, except: 

    [pth,fname] = fileparts(fileNames{ii});

    imwrite(im, [pth filesep fname '.tif'], 'tiff');

end

Or, for added convenience when using uigetfile,

if filename ~= 0
    img(pathname, filename);

else
    error('No file selected.');
end

with

function img( pathnames, filenames)

    if ~iscell(pathnames)
         img( {pathnames}, {filenames} ); 
            return; 
    end   

    for ii = 1:numel(pathnames)

        im = imread([pathnames{ii} filenames{ii}]);

        ...

        [do operations on im]

        ...

        [~,basename] = fileparts(filenames{ii});
        imwrite(im, [basename '.tif'], 'tiff');

    end

end

Upvotes: 1

Related Questions