
% STEP 1: Image Conditioning and Background Subtraction

% This script performs two functions.  First, it performs median filtering of each image.  Second, it subtracts background images from signal images.
% There are eight slides to be analyzed.

% 1. Reset variables & close image windows to free up memory.

clear, close all;

% 2. These lines define which of the 20 images are background images (values set to zero) and which are signal images (values set to greater than zero).
%    The values (for the signal images) provide the index of the specific background image to subtract from that signal image.

SA = [4 3 0 0 7 8 0 0 11 12 0 0 14 0 17 0 0 0 17 18];    % Use for Slides 1,2,3,4
SB = [4 3 0 0 7 8 0 0 11 12 0 0 15 16 0 0 19 20 0 0];    % Use for Slides 5,6,7,8

% 3. Iterate over the eight slides (as we are processing all images in parallel).

for D = 1:8

    % Define the directory to be used
    
    DIR_NAME = strcat('./IMAGES/SL',num2str(D),'/');
    
    % Define the list of 20 files in that directory
    
    FILELIST = dir(strcat(DIR_NAME,'SL',num2str(D),'*.Tif'));

    % Iterate over the set of 20 files
    
    for i = 1:size(FILELIST)
    
        % Obtain the appropriate index value (which identifies this scan as a background or signal image, and if a signal image, then what its 
        % corresponding background image is)
        
        if (D <= 4)
            my_index = SA(i);
        else
            my_index = SB(i);
        end
        
        % If this file not a background image (according to the indicies in the SA or SB variables)...
                
        if (my_index > 0)
         
           % Load signal image and appropriate background
       
           A = imread(strcat(DIR_NAME,FILELIST(i).name));           % Signal Image
           B = imread(strcat(DIR_NAME,FILELIST(my_index).name));    % Background Image
       
           % Identify the file currently being processed
            
            [FILELIST(i).name mat2str(size(A))]
            
           % Apply a [3 x 3] median filter to each image (to reduce noise)
       
           A1 = medfilt2(A,[3 3]);
           B1 = medfilt2(B,[3 3]);
                     
           % Subtract median-filtered background image from median-filtered signal image
       
           C = imsubtract(A1,B1);
           
           % Generate new file name
           
           new_name = strcat(DIR_NAME,FILELIST(i).name,'.sub');

           % Save image
           
           imwrite(C,new_name,'tif');
           
           % Display image
           
           imagesc(C);

           % To ease termination of the routine (if it becomes neccesary)...
                      
            pause(1);
 
       end
        
    end

end

% 4. Reset variables & close image windows to free up memory.

clear, close all

