1

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.

  • `if contains( trainIm(i).name, 'neg' )`, with an `else` for everything else? – Wolfie Dec 10 '21 at 16:04
  • What is the problem? Do you get an error? The new directories are not created? The images are not saved? Which part of your code works and which one not? – RobertoT Dec 10 '21 at 16:04
  • @RobertoT I don't get any error and the directories are created correctly but the images are not saved in them. – user14287399 Dec 10 '21 at 16:07
  • Never tried to use `save` to save an actual image, only matrixes or structs. Maybe you should try other ways instead of that function. Possible ways: https://es.mathworks.com/matlabcentral/answers/23481-how-to-save-image & https://stackoverflow.com/questions/22344884/how-to-save-an-image-in-matlab – RobertoT Dec 10 '21 at 18:24

1 Answers1

0

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
selene
  • 394
  • 5
  • 17