AVFoundation - Detect face and crop face area?

MegaManX

As title says i want to detect face and then to crop just the face area. This is what I have so far:

- (void) captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {

for (AVMetadataObject *face in metadataObjects) {
    if ([face.type isEqualToString:AVMetadataObjectTypeFace]) {

        AVCaptureConnection *stillConnection = [_stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
        stillConnection.videoOrientation = [self videoOrientationFromCurrentDeviceOrientation];
        [_stillImageOutput captureStillImageAsynchronouslyFromConnection:stillConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
            if (error) {
                NSLog(@"There was a problem");
                return;
            }

            NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *stillImage = [UIImage imageWithData:jpegData];

            CIDetector *faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context:[CIContext contextWithOptions:nil] options:nil];
            CIImage *ciimage = [CIImage imageWithData:jpegData];

            NSArray *features = [faceDetector featuresInImage:ciimage];
            self.captureImageView.image = stillImage;

            for(CIFeature *feature in features) {
                if ([feature isKindOfClass:[CIFaceFeature class]]) {
                    CIFaceFeature *faceFeature = (CIFaceFeature *)feature;

                    CGImageRef imageRef = CGImageCreateWithImageInRect([stillImage CGImage], faceFeature.bounds);
                    self.detectedFaceImageView.image = [UIImage imageWithCGImage:imageRef];
                    CGImageRelease(imageRef);
                }
            }
            //[_session stopRunning];
        }];
    }
}

}

This code works partially, it can detect face, but it can not crop part with face, it is always cropping the wrong area, it cropping something at all. I have been browsing stack for answers, trying this and that, but to no avail.

MegaManX

Here is the answer

- (void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

// when do we start face detection
if (!_canStartDetection) return;

CIImage *ciimage = [CIImage imageWithCVPixelBuffer:CMSampleBufferGetImageBuffer(sampleBuffer)];
NSArray *features = [_faceDetector featuresInImage:ciimage options:nil];

// find face feature
for(CIFeature *feature in features) {

    // if not face feature ignore
    if (![feature isKindOfClass:[CIFaceFeature class]]) continue;

    // face detected
    _canStartDetection = NO;
    CIFaceFeature *faceFeature = (CIFaceFeature *)feature;

    // crop detected face
    CIVector *cropRect = [CIVector vectorWithCGRect:faceFeature.bounds];
    CIFilter *cropFilter = [CIFilter filterWithName:@"CICrop"];
    [cropFilter setValue:ciimage forKey:@"inputImage"];
    [cropFilter setValue:cropRect forKey:@"inputRectangle"];
    CIImage *croppedImage = [cropFilter valueForKey:@"outputImage"];
    UIImage *stillImage = [UIImage imageWithCIImage:ciimage];
}

}

Note that I used this time AVCaptureVideoDataOutput, here is that code:

// set output for face frames
AVCaptureVideoDataOutput *output2 = [[AVCaptureVideoDataOutput alloc] init];
[_session addOutput:output2];
output2.videoSettings = @{(NSString*)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA)};
output2.alwaysDiscardsLateVideoFrames = YES;
dispatch_queue_t queue = dispatch_queue_create("com.myapp.faceDetectionQueueSerial", DISPATCH_QUEUE_SERIAL);
[output2 setSampleBufferDelegate:self queue:queue];

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to crop the detected face image in opencv java

Detect face then autocrop pictures

Is there any Android API to detect face inside an image?

Crop off Parts of the Image that does not include the Face

Python OpenCV live face detection crop saved

Crop face from the CameraSource

Showing texts over the face of a Box based on the visible area on zooming in/out

Crop Detected Face in Android

Three.js Calculate the Area of Geometry Face (Face3)

Swift: CoreImage Face Detection will Detect Every round object as a Face

How to detect whose face this is in OpenCV?

How to crop face regions using convexhull polygons

How to crop face from landmarks in MATLAB?

How to detect coordinates of left and right eye using android face detection

Face detection, Face Recognition

Matlab: Working on obtaining detected face using 'Detect and Track Multiple Face'

which face area should be cropped out for recognition

Using affectiva to detect a real face

Detect face up position with sensors in iOS

How can we detect face using OpenCV

how to detect upside down face?

Calculate surface area and normal for each face of an arbitrary hexahedron

Face detection of a face with mask

Detect if face is within a circle

AWS recognition face API: Crop teeth section (mouth) from face

How to define the area of the texture to apply to a face

Python: Image face detection and sorting into face and no face

Detect if face is in fixed area of video frame

Microsoft Azure Face API - Face detect return values, but not return faceId

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive