MATLAB: Problem in writing files

digital image processingimage processingMATLAB

hello everyone. i have to folders of images, one contains images named 1.jpg…99.jpg, and the other one named 100.jpg…120.jpg
i want to crop them with a mask and then write them in the same folder. my code works for the first folder. it works even for the second folder but it doesnt write the result images.
could anyone help me please?
this is my code:
img = imread('100.jpg');
h_im = imshow(img);
e = imfreehan
BW = createMask(e,h_im);
BW(:,:,2) = BW;
BW(:,:,3) = BW(:,:,1);
ROI = img;
ROI(BW == 1) = 1;
figure, imshow(ROI);
surf_read_dir='E:\phd\zahra taati\extract only heart\crop100-112\';
files=dir('E:\phd\zahra taati\extract only heart\crop100-112\*.jpg');
ROI2=ROI
for k=1:size(files)
fdir = strcat(surf_read_dir , files(k).name);
img = imread(fdir);
ROI2 = img;
ROI2(BW == 1) = 1;
pickind='jpg';
strtemp=strcat('croped',int2str(k),'.',pickind);
imwrite(ROI2,strtemp);
end

Best Answer

The problem is likely caused by the fact that your images are actually written to a different directory than you think.
I strongly recommend using fullfile rather than trying to concatenate paths and filenames.
Start with something like this:
D = 'E:\phd\zahra taati\extract only heart\crop100-112\';
S = dir(fullfile(D,'*.jpg'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
I = imread(F);
J = ... do whatever you want with image I
G = fullfile(D,['cropped',S(k).name]); % you forgot the path here!
imwrite(J,G);
end
If you want to change the file extension then use fileparts to get the filename, then simply append the desired extension to the name.