Pairwise image subtraction from a folder

1 次查看(过去 30 天)
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.

采纳的回答

DGM
DGM 2022-4-5
编辑:DGM 2022-4-5
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 个评论
Shaurov Das
Shaurov Das 2022-4-5
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!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Images 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by