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

3 次查看(过去 30 天)
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 个评论
Mustafa Yildiz
Mustafa Yildiz 2020-3-29
>> 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

请先登录,再进行评论。

回答(1 个)

MaryD
MaryD 2020-3-29
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.

类别

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