-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloping.m
62 lines (47 loc) · 1.95 KB
/
cloping.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
% Specify the folder containing the original images
inputFolder = 'C:\Users\25197\OneDrive\Desktop\Friends\orginal_other';
% Specify the folder for saving the cropped images
outputFolder = 'C:\Users\25197\OneDrive\Desktop\Friends\Train\other';
% Create the output folder if it doesn't exist
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
% Create a face detector object
faceDetector = vision.CascadeObjectDetector();
% Get a list of all image files in the input folder
imageFiles = dir(fullfile(inputFolder, '*.jpg')); % Update the extension if your images have a different format
% Loop through each image
for i = 1:length(imageFiles)
% Read the original image
originalImage = imread(fullfile(inputFolder, imageFiles(i).name));
% Detect faces in the image
bbox = step(faceDetector, originalImage);
% Check if any faces are detected
if ~isempty(bbox)
% Crop the first detected face
x = bbox(1, 1);
y = bbox(1, 2);
width = bbox(1, 3);
height = bbox(1, 4);
% Crop the image
croppedImage = imcrop(originalImage, [x, y, width, height]);
% Display the original and cropped images
figure;
subplot(1, 2, 1);
imshow(originalImage);
title(['Original Image - ' imageFiles(i).name]);
subplot(1, 2, 2);
imshow(croppedImage);
title(['Cropped Image - ' imageFiles(i).name]);
% Specify the file path for saving the cropped image
[~, imageName, imageExt] = fileparts(imageFiles(i).name);
savePath = fullfile(outputFolder, [imageName '_cropped' imageExt]);
% Save the cropped image
imwrite(croppedImage, savePath);
disp(['Cropped image with detected face saved at: ' savePath]);
else
disp(['No faces detected in image: ' imageFiles(i).name]);
end
% Close figures to avoid cluttering the display
close all;
end