MATLAB: Multiple face detection and cropping from multiple images

detecting multiple faces from multiple imagesmultiple image reading

I want to read multiple images from directory where each image contains multiple faces, I want to detect faces from each image and want to crop the detected faces and want to save these faces into another directory.
I tried the following code, It performs the face dection and cropping process on only one image. I want to perform face detection and cropping process on all of the images present in the image directory.
location = 'E:\fer1\frames\*.jpg'; % folder in which your images exists
ds = imageDatastore(location) % Creates a datastore for all images in your folder
% Loop through the datastore, read and display each image in its own window.
while hasdata(ds)
img = read(ds) ; % read image from datastore
figure, imshow(img); % creates a new window for each image
end
%figure(1);
%imshow(img);
FaceDetect = vision.CascadeObjectDetector;
FaceDetect.MergeThreshold = 7 ;
BB = step(FaceDetect, img);
figure(2);
imshow(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);
end

Best Answer

imds = imageDatastore ( 'face' , ...
'IncludeSubfolders' , true, ...
'LabelSource' , 'foldernames' );
idx = randperm (numel (imds.Files), 4);
j = 1;
figure
for t = 1: 4
img = readimage (imds, idx (t));
FaceDetect = vision.CascadeObjectDetector;
FaceDetect.MergeThreshold = 7;
BB = step (FaceDetect, img);
figure (2);
imshow (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, [j, '.jpg' ])
end
end
Related Question