Maniganda saravanan
Maniganda saravanan

Reputation: 2198

Transform an Image using CIFaceFeature in iOS

I use CIDetector and CIFaceFeature to detect face on the front facing camera. Also trying to place a hat on the head. The hat is placing fine when the head is straight. If I tilt my head the hat goes small and goes away from head.

Code use to add the hat,

self.hatImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:selectedImageName]];
self.hatImgView.contentMode = UIViewContentModeScaleAspectFit;
[self.previewView addSubview:self.hatImgView];

Detecting the face and movement,

- (void)detectedFaceController:(DetectFace *)controller features:(NSArray *)featuresArray forVideoBox:(CGRect)clap withPreviewBox:(CGRect)previewBox
{
for (CIFaceFeature *ff in featuresArray) {
    CGRect faceRect = [ff bounds];
    
    //isMirrored because we are using front camera
    faceRect = [DetectFace convertFrame:faceRect previewBox:previewBox forVideoBox:clap isMirrored:YES];
    
    float hat_width = self.hatImgView.image.size.width;
    float hat_height = self.hatImgView.image.size.height;
    int head_start_y = 330.0; //part of hat image is transparent
    int head_start_x = 60.0;

    float width = faceRect.size.width * (hat_width / (hat_width - head_start_x));
    float height = width * hat_height/hat_width;
    int y = faceRect.origin.y - (height * head_start_y) / hat_height;
    int x = faceRect.origin.x - (head_start_x * width/hat_width);
    [UIView animateWithDuration:0.3 animations:^{
            [self.hatImgView setTransform:CGAffineTransformRotate(CGAffineTransformIdentity, (DegreesToRadians(-ff.faceAngle)))];
            self.hatImgView.frame =  CGRectMake(x, y, width + 60.0f, height + 60.0f);
     }];
} 
}

Does anyone know how to transform the hat with the head? All helps are appreciated!!

Upvotes: 1

Views: 483

Answers (0)

Related Questions