Pairwise image subtraction from a folder

1 view (last 30 days)
Hi, I have a folder with 30 images (saved them as .mat file). I want to get the difference image and save them, therefore, my code should produce 15 images. I want (image1-image2), (image3-image4), (image5-image6), (image7-image8) and so on. The code I've written is attached below:
for j = 1:length(filenames_asl)
label_name = char(filenames_asl(j)); % filename_asl is the string array where the sequential filenames are saved
control_name = char(filenames_asl(j+1)); % Second image (filename)
label = load(strcat(foldername_asl, '/', label_name)).im1; % Loading the first image
control = load(strcat(foldername_asl, '/', control_name)).im1; % Loading the second image
asl_image = label - control; % Getting difference image
imagename_asl = fullfile(dir_asl, strcat(im_name_asl, '_', num2str(j), '.mat')); % Specifying name and location for saving the difference images
save(imagename_asl); %% Saving the difference image
j = j+2; % Increment of the loop index to skip the second image at the beginning of the next iteration
end
I have faced two problems:
  1. I'm getting 29 images running this code, I'm not sure why.
  2. I'm getting an error at the end of the loop saying 'Index must not exceed 30'.
Can anyone please help with this problem? Thanks in advance.

Accepted Answer

DGM
DGM on 5 Apr 2022
Edited: DGM on 5 Apr 2022
Trying to increment j won't work like that. Just specify a vector that skips every other integer. In this case, label_name has an odd-integer name; control_name has an even-integer name.
for j = 1:2:length(filenames_asl) % every other
label_name = char(filenames_asl(j)); % filename_asl is the string array where the sequential filenames are saved
control_name = char(filenames_asl(j+1)); % Second image (filename)
label = load(strcat(foldername_asl, '/', label_name)).im1; % Loading the first image
control = load(strcat(foldername_asl, '/', control_name)).im1; % Loading the second image
asl_image = label - control; % Getting difference image
imagename_asl = fullfile(dir_asl, strcat(im_name_asl, '_', num2str(j), '.mat')); % Specifying name and location for saving the difference images
save(imagename_asl); %% Saving the difference image
end
Your output files will be numbered with odd integers unless you change it to use something other than j. If you want them to be numbered sequentially 1-15, then:
imagename_asl = fullfile(dir_asl, strcat(im_name_asl, '_', num2str((j+1)/2), '.mat')); % Specifying name and location for saving the difference images
  1 Comment
Shaurov Das
Shaurov Das on 5 Apr 2022
Thank you so much! It worked! I also tried it with while loop with a counter update in each iteration. That works too. I like your solution better. Thank again!

Sign in to comment.

More Answers (0)

Categories

Find more on Images in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!