Face detection is something I’ve been interested in for a while now. Previously to get it working on the iPhone we had to use Open CV but with iOS5 Apple have included native face detection as a part of the Core Image framework. It’s very simple to get FD up and running without any fuss, as I’m going to show you in this tut, and there’s a whole lot more you can do with it such as eye and mouth detection and hooking it up to a video stream from the camera. However to keep it simple I’m going to detect a face from an image that’s already in the app.
So here it is, one simple method. First we need to convert our image into a CIImage. Then we create a CIDetector and parse our image into it. The CIDetector returns an array of all the face features contained within our image. Then we run a for loop to cycle through and extract the faces. Now we can get the frame of each face and do whatever we like with it, I’m putting a black border around it and then adding an image of a cat over the top. In the example code I’ve added a UIButton that toggles the cat on and off. Don’t forget to import CoreImage. Simple. Download the example project here
-(void)detectFacesFromImage:(UIImageView*)aUIImageView{ CIImage* image = [CIImage imageWithCGImage:aUIImageView.image.CGImage]; CIDetector* detector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:[NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]]; NSArray* features = [detector featuresInImage:image]; for(CIFaceFeature* faceFeature in features) { UIView* faceDetectView = [[UIView alloc] initWithFrame:faceFeature.bounds]; //create a border around the detected face faceDetectView.layer.borderWidth = 1; faceDetectView.layer.borderColor = [[UIColor blackColor] CGColor]; [self.faceView addSubview:faceDetectView]; //place cat over the face self.catFaceView.frame = faceFeature.bounds; } }