-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUIImage+FaceDetection.m
45 lines (31 loc) · 1.51 KB
/
UIImage+FaceDetection.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
#import "UIImage+FaceDetection.h"
@implementation UIImage (FaceDetection)
- (NSArray *)facesWithAccuracy :(NSString *)detectorAccuracy {
CIImage *coreImageRepresentation = [[CIImage alloc] initWithImage:self];
CIDetector* detector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:[NSDictionary dictionaryWithObject:detectorAccuracy forKey:CIDetectorAccuracy]];
NSArray *features = [detector featuresInImage:coreImageRepresentation];
return features;
}
- (CIFaceFeature *)largestFaceWithAccuracy :(NSString *)detectorAccuracy {
NSArray *faces = [self facesWithAccuracy:detectorAccuracy];
float currentLargestWidth = 0;
CIFaceFeature *largestFace;
for (CIFaceFeature *face in faces) {
if (face.bounds.size.width > currentLargestWidth) {
largestFace = face;
currentLargestWidth = face.bounds.size.width;
}
}
return largestFace;
}
- (UIImage *)croppedAroundLargestFaceWithAccuracy :(NSString *)detectorAccuracy {
CIFaceFeature *largestFace = [self largestFaceWithAccuracy:detectorAccuracy];
CIImage *coreImage = [[CIImage alloc] initWithImage:self];
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *faceImage =
[coreImage imageByCroppingToRect:largestFace.bounds];
UIImage *croppedImage = [UIImage imageWithCGImage:[context createCGImage:faceImage
fromRect:faceImage.extent]];
return croppedImage;
}
@end