1

使用 Matlab,我想根据名称将同一目录中存在的图像移动到两个新目录中。

在目录中有两组图像名称:'neg-0.pgm', 'neg-1.pgm', 'neg-2.pgm', ... 和 'pos-0.pgm', 'pos -1.pgm','pos-2.pgm',...

我尝试了不同的功能来更改图像目录,但我无法成功操作。

我的代码是:

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

我没有收到任何错误,但新目录仍然是空的。

4

1 回答 1

0

我认为有两个问题正在发生:

1 -strcmp在 if 语句中使用通配符 (*) 可能无法正常工作

2 - 使用movefile而不是save. https://www.mathworks.com/help/matlab/ref/movefile.html

请参见下面的代码(在创建新目录后使用):

    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
于 2021-12-10T22:44:51.637 回答