简体   繁体   中英

Changing all images in a specific folder to type jpeg in matlab

I need to change (and not to keep the old) all the images in a specific folder (and subfolders) to format of type jpeg and save all of the images in one folder. I'm new to Matlab. What I tried:

function convertImages(Folder,ImgType)
Imgs = dir(fullfile(Folder,ImgType));
for i=1:numel(Imgs)
    oldFilename = fullfile(Folder, Imgs(i).name);
    [~,name,~] = fileparts(Imgs(i).name);
    newFilename = fullfile(Folder, strcat(name, '.jpg'));
    imwrite(imread(oldFilename), newFilename);
end
end

When I try to run convertImages('images','png'), Imgs is empty - but I have in the folder 6 files and two of them are png.

When I try to run convertImages('images','*') Imgs loads 8 files, two of them are '.' and '..' , two files I cannot see and it crashes matlab.

Any help will be appreciated!

First, the '.' and '..' stand for the current and parent directories.
Now in order to support multiple types what I would do is make ImgType a cell array with all possible types. For example:

ImgType = {'.png','gif'};

and use

Imgs = dir(fullfile(Folder,'*')); 

In order to avoid the first 2 entries of Imgs just start the loop from 3 instead of 1. Finally in order to check the file type you can do:

[~,name,ext] = fileparts(Imgs(i).name);
if any(cellfun(@(x) strcmp(x,ext), ImgType))
...
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM