如何使用循环插入噪声并将多个图像保存在不同的文件夹中?(matlab)

how to insert noise and save multiple images in different folders using a loop?(matlab)

我是图像处理方面的新手,我需要帮助。我有一个包含 1000 张图像的文件夹(数据集),我想插入具有不同密度噪声(0.01、0.02 和 0.03)的噪声 'salt & pepper',我使用此行来执行此操作:

 im = imread('C:\Users\SAMSUNG\Desktop\AHTD3A0002_Para1.tif');
 J = imnoise(im,'salt & pepper',0.01);

请帮助我这样做:我想将结果保存在 3 个文件夹中(data1 包含 d=0.01 噪声后的图像,data2 包含 d=0.02 噪声后的图像,data3 包含 d= 噪声后的图像0.03).

任何建议并提前致谢

使用 2 个 for 循环的简单解决方案。

%save the noise parameter.
noise = [0.01,0.02,0.03];

for i = 1:1000

%we generate the filename (you can adapt this code)
imname = fullfile('C:\Users\SAMSUNG\Desktop\',sprintf('AHTD3A0002_Para%d.tif',i))
%read the image.
im = imread(imname);

for j = 1:length(noise)

%apply the noise
J = imnoise(im,'salt & pepper',noise(j));
%save image in the right folder
imwrite(J,fullfile('C:\Users\SAMSUNG\Desktop',sprintf('folder%d',j)));

end
end

以下代码将允许您 select 文件夹并在 3 个不同的文件夹中创建噪声图片。它只会 select 您可以在代码中修改的 '*.tif' 文件。如果您需要创建更多噪音级别,请创建一个循环来动态命名文件夹和文件。

% get dir
folderX = uigetdir();

% get files
picFiles = dir('*.tif');

% loop over the files and save them with the noise
for ii = 1:length(picFiles)

    currentIm = imread([folderX, '\', picFiles(ii).name]);

    % create folders if not exist
    if ~exist([folderX,'\noise_0.01\'], 'dir')
        % create folders
        mkdir([folderX,'\noise_0.01\']);
    end
    if ~exist([folderX,'\noise_0.02\'], 'dir')
        % create folders
        mkdir([folderX,'\noise_0.02\']);
    end
    if ~exist([folderX,'\noise_0.03\'], 'dir')
        % create folders
        mkdir([folderX,'\noise_0.03\']);
    end   

    J1 = imnoise(currentIm,'salt & pepper',0.01);       
    imwrite(J1,fullfile([folderX, '\noise_0.01\', picFiles(ii).name]));    

    J2 = imnoise(currentIm,'salt & pepper',0.02);    
    imwrite(J2,fullfile([folderX, '\noise_0.02\', picFiles(ii).name]));

    J3 = imnoise(currentIm,'salt & pepper',0.03);
    imwrite(J3,fullfile([folderX, '\noise_0.03\', picFiles(ii).name]));

end