Detect face from multiple image, crop it and save it in different file.

1 view (last 30 days)
I have face dataset and trying to detect faces, crop them and save them in different file. I have this code but its giving error "Unable to open file "C:\Users\mstfy\Desktop\Matlab\alex\affine1\" for writing. You might not have write permission." i tried to change the file and location but its still not working. Also i am not really sure that this code will read all images, detect every face and save it. Can anyone please check it and help me with it please ?
location = 'C:\Users\mstfy\Desktop\Matlab\alex\newdata\*.jpg';
croppedimg = 'C:\Users\mstfy\Desktop\Matlab\alex\affine1\';
imds = imageDatastore ( 'C:\Users\mstfy\Desktop\Matlab\alex\newdata' , ...
'IncludeSubfolders' , true, ...
'LabelSource' , 'foldernames' );
idx = randperm (numel (imds.Files), 16);
j = 1;
figure
for t = 1: 16
img = readimage (imds, idx (t));
FaceDetect = vision.CascadeObjectDetector;
FaceDetect.MergeThreshold = 7;
BB = step (FaceDetect, img);
for i = 1: size (BB, 1)
rectangle ( 'Position' , BB (i, :), 'LineWidth' , 3, 'LineStyle' , '-' , 'EdgeColor' , 'r' );
end
for i = 1: size (BB, 1)
J = imcrop (img, BB (i, :));
figure (3);
subplot (6, 6, i);
imshow (J);
j = j + 1;
imwrite (J,croppedimg,'jpg' )
end
end
  2 Comments
Ameer Hamza
Ameer Hamza on 29 Mar 2020
Can you tell which line give this error. Paste the complete error message.
Mustafa Yildiz
Mustafa Yildiz on 29 Mar 2020
>> Untitled3
Error using imwrite (line 528)
Unable to open file "C:\Users\mstfy\Desktop\Matlab\alex\affine1\" for writing. You
might not have write permission.
Error in Untitled3 (line 23)
imwrite (J,croppedimg,'jpg' )
This is the complete error message

Sign in to comment.

Answers (1)

MaryD
MaryD on 29 Mar 2020
If you want to read jpg images from one folder and save cropped images with same name and format but in different folder you can try this
srcFile=dir('C:\Users\mstfy\Desktop\Matlab\alex\newdata\*.jpg');
for i=1:length(srcFile)
filename=strcat('C:\Users\mstfy\Desktop\Matlab\alex\newdata\',srcFile(i).name);
I=imread(filename);
%here is the part of code which create cropped image named J
filename=strcat('C:\Users\mstfy\Desktop\Matlab\alex\affine1\',srcFile(i).name);
imwrite(J,filename);
end
You can of course modify this piece to save your images with different names but to avoid the error you recievieng you should try include file name and format in filename and then use imwrite.

Categories

Find more on Display Image 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!