Search code examples
matlabfor-loopnoisesave-image

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


I am new in image processing and I want help. I have a folder (dataset) that contains 1000 images and I want to insert noise 'salt & pepper' with different density noise (0.01,0.02 and 0.03) , I used this line to do this:

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

Please help me to do this : I want to save the result in 3 folder ( data1 contains images after noise with d=0.01, data2 contains images after noise with d=0.02 and data3 contains images after noise with d=0.03).

any suggestation and thanks in advance


Solution

  • Following code will allow you to select the folder and create the noised pictures in 3 different folders. It will only select the '*.tif' files which you can modify in the code. And if you need to create more noise levels, create a loop to name the folders and files dynamically.

    % 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