Compare two folders for matching images
5 views (last 30 days)
Show older comments
Hi there,
I have two folders of images and I want to save the images from folder 1 that have the same names in folder 2 into another folder.
For examples Folder 1 contains 2600 images and folder 2 contains 1300 images. I tried to write the code but I got
Matrix dimensions must agree.
Error in Untitled (line 15)
if im_name1 == im_name2
clc;
clear all;
out_path ='____\New folder\';
folder1 = '____\folder1\';
folder2 = '____\folder2\';
fileInfo1 = dir(fullfile(folder1, '*.jpg'));
fileInfo2 = dir(fullfile(folder2, '*.jpg'));
for k = 1 : length(fileInfo1)
for k2 = 1 : length(fileInfo2)
im = imread([folder1 fileInfo1(k).name]);
im_name1 = [fileInfo1(k).name(1:end-4) '.jpg'] ;
im_name2 = [fileInfo2(k2).name(1:end-4) '.jpg'];
if im_name1 == im_name2
imwrite(im, fullfile(out_path, im_name2));
end
fprintf('Processing: %d/%d\n', k2,length(fileInfo2));
end
end
How to solve this issue?
0 Comments
Accepted Answer
Walter Roberson
on 13 Aug 2021
Use strcmp() to compare character vectors.
Or convert to string, such as
im_name1 = fileInfo1(k).name(1:end-4) + ".jpg" ;
im_name2 = fileInfo2(k2).name(1:end-4) + ".jpg";
2 Comments
Walter Roberson
on 13 Aug 2021
But you can do even better: you can avoid the loop using ismember()
names1 = {fileInfo1.name};
names2 = {fileInfo2.name};
is_present = ismember(names1, names2);
same_names = names1(is_present);
source_names = fullfile(folder1, same_names);
dest_names = fullfile(out_path, same_names);
cellfun(@(s,d) copyfile(s,d), source_names, dest_names);
More Answers (0)
See Also
Categories
Find more on Image Segmentation and Analysis 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!