MATLAB: Problem in imwrite new images into new directory

imwrite

Hi, I wish to output my new modified images to a new directory, but I got this error "Struct contents reference from a non-struct array object". Im sorry if there is more than one problem needs to be fixed here. I tested the first loop was working well, but not for the second loop. I guess the problem comes from the loop for writing images to a new directory. Thanks for any suggestion in advance.
img_folder='/Users/MATLAB/Faces';
imgs =dir(fullfile(img_folder, '*.jpg'));
%output folder
distFolder = '/Users/MATLAB/Faces/New';
if isdir(distFolder)
rmdir(distFolder, 's');
end
mkdir(distFolder);
for i=1:length(imgs) %loop for modifed images
imgsName = imgs(i).name;
fullName=fullfile(img_folder,imgsName);
img = im2uint8(imread(imgsName));
img = img(:,:);
image_thresholded = zeros(size(img));
for ii=1:size(img,1)
for jj=1:size(img,2)
pixel=img(ii,jj);
if pixel<10
new_pixel=11;
elseif pixel>240
new_pixel=239;
else
new_pixel = pixel;
end
image_thresholded(ii,jj)=new_pixel;
end
end
for k= 1:length(image_thresholded) % loop reads the new images into new directory
newimgsName= image_thresholded(k).name;
thresholdImg = (sprintf('%s.jpg', k));
fulldestination = fullfile(distFolder, newimgsName);
imwrite(image_thresholded,thresholdImg,fulldestination,'jpg')
end
end

Best Answer

Note: when reporting an error always give us the full error message. In particular, you've removed the part that tells you which line is throwing the error, so we're left to guess. Thankfully, here it's obvious where the error comes from.
You define image_thresholded as a matrix with:
image_thresholded = zeros(size(img));
Yet later on, you try to use it as if it were a structure, as that typically returned by dir
newimgsName= image_thresholded(k).name;
This, of course, is not going to work. I suspect that you meant to use imgs, not image_thresholded.
Also note that this whole loop:
for ii=1:size(img,1)
for jj=1:size(img,2)
pixel=img(ii,jj);
if pixel<10
new_pixel=11;
elseif pixel>240
new_pixel=239;
else
new_pixel = pixel;
end
image_thresholded(ii,jj)=new_pixel;
end
end
can be replaced by
image_thresholded = min(max(img, 11), 239);
if intensity 10 is supposed to be changed to 11 as well as anything below 10 and intensity 240 is supposed to be changed to 239 as well as anything above 240.
If you want the exact same thing that your current code does, which changes [8, 9, 10, 11, 12] to [11, 11, 10, 11, 12] (not very logical in my opinion), then:
image_thresholded = img;
image_thresholded(img < 10) = 11;
image_thrreshold(img > 240) = 239;