Pull to refresh

Face detection в iOS 5 SDK

Reading time3 min
Views2.9K
iOS SDK доступен уже длительное время, но каждый iOS разработчик знает, что использовать новое API в своих приложениях еще очень рано, так как клиент заинтересован в совместимости своих программ со старыми версиями этой ос.

Но все нашлась парочка вкусностей в новом SDK. Первым бросился в глаза метод для UIViewController viewWillUnload, который так был нужен несколько месяцев назад.
Весь перечень нововведений для iOS 5 смотреть здесь.
В списке добаленых фреймворков вызывает интерес CoreImage и в частности CIDetector.h.

Класс CIDetector создан в помощ поиска и определения лиц на изображении, что мы сейчас попробуем вкратце проделать.


Используем XCode 4.2 with iOS 5 SDK.

Создаем проект

Очень рекомендую отключать «Use Automatic Reference Counting».

Подключаем в проект framework CoreImage

image

Создаем UIViewController

#import <UIKit/UIKit.h>
 
@interface RootViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    IBOutlet UIImageView *imageView;
    IBOutlet UILabel *label;
    CIDetector *detector;
}
 
@end


Загружаем картинку используя UIImagePickerController

- (IBAction)onImport:(id)sender
{
    UIImagePickerController *vc = [[UIImagePickerController alloc] init];
    vc.delegate = self;
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:vc animated:YES];
    [vc release];
}


Свой девайс я не апгрейдил до iOS 5, потому все действия будут просходить на симуляторе с импортом из галереи, а не камеры.

Определяем лица на картинке

- (IBAction)onRecognize:(id)sender
{
    detector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:[NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]];
 
    NSDate *date = [NSDate date];
 
    NSArray *features = [detector featuresInImage:
                            [[[CIImage alloc] initWithCGImage:imageView.image.CGImage] autorelease]
                        ];
 
    NSTimeInterval ti = fabs([date timeIntervalSinceNow]);
 
    label.text = [NSString stringWithFormat:@"Time: %0.3f\nFaces: %i",ti,[features count]];
 
    UIGraphicsBeginImageContext(imageView.image.size);
 
    CGContextRef ctx = UIGraphicsGetCurrentContext();
 
    CGContextDrawImage(ctx, CGRectMake(00, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
 
 
    for (CIFeature *feature in features) 
    {
        CGRect r = feature.bounds;
 
        CGContextSetStrokeColor(ctx, CGColorGetComponents([UIColor yellowColor].CGColor));
        CGContextSetLineWidth(ctx, 1.0f);
 
        CGContextBeginPath(ctx);
        CGContextAddRect(ctx, r);
        CGContextClosePath(ctx)
        CGContextStrokePath(ctx);
 
    }
    imageView.image = [UIImage imageWithCGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage scale:1.0f orientation:UIImageOrientationDownMirrored];
    UIGraphicsEndImageContext();
 
}
 


Результат

В документации экземпляр класса CIFeature дает информацию только о рамке лица и о своем типе, но можна надеяться, что когда в Apple полностью передерут OpenCV, то можно будет ждать обновлений класса (IMHO).





EDIT: Исправлен лик в методе onImport:
Tags:
Hubs:
Total votes 31: ↑27 and ↓4+23
Comments11

Articles