Home > Enterprise >  Matlab move multiple files in a directory
Matlab move multiple files in a directory

Time:12-11

Using Matlab, I want to move the images present in the same directory in two new directories according to their name.

In the directory there are two set of image' name: 'neg-0.pgm', 'neg-1.pgm', 'neg-2.pgm', ... and 'pos-0.pgm', 'pos-1.pgm', 'pos-2.pgm', ...

I tried different functions to change the image directory but I wasn't able to make the operation successfully.

My code is:

if not(exist('./CarDataset/TrainImages/PosImages', 'dir'))
    mkdir ./CarDataset/TrainImages PosImages
end

if not(exist('./CarDataset/TrainImages/NegImages', 'dir'))
    mkdir ./CarDataset/TrainImages NegImages
end

trainIm = dir('./CarDataset/TrainImages/*.pgm');

for i = 1:size(trainIm, 1)
    if(strcmp(trainIm(i).name, 'neg*.pgm'))
        save(fullfile('./CarDataset/TrainImages/NegImages', ['neg-' num2str(i) '.pgm']))
    end
end

I don't get any error but the new directories are still empty.

CodePudding user response:

I believe there are two issues going on:

1 - using strcmp in the if statement with a wildcard (*) may not work properly

2 - use movefile instead of save. https://www.mathworks.com/help/matlab/ref/movefile.html

See below code (use after you have made the new directories):

    origDir = './CarDataset/TrainImages/';
    trainIm = dir([origDir '*.pgm']);
    
    for i = 1:size(trainIm, 1)
        origFile = trainIm(i).name;
        if contains(trainIm(i).name, 'neg'))
             newDir = './CarDataset/TrainImages/NegImages/';
        else
             newDir = './CarDataset/TrainImages/PosImages/';
        end
        movefile([origDir trainIm(i).name], newDir);
    end
  • Related