Skip to content

Instantly share code, notes, and snippets.

@dimpler03
Last active May 25, 2018 05:13
Show Gist options
  • Save dimpler03/94f2782843c964233eb0a26da4384c66 to your computer and use it in GitHub Desktop.
Save dimpler03/94f2782843c964233eb0a26da4384c66 to your computer and use it in GitHub Desktop.
Detecting face rects using CIDetector
func detectFaceIn(imageBuffer: CVImageBuffer) {
let image = CIImage(cvImageBuffer: imageBuffer)
let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy)
let faces = faceDetector?.features(in: image)
let imageSize = CVImageBufferGetDisplaySize(imageBuffer)
var actualRect = CGRect()
for face in faces! {
actualRect = CGRect(x: face.bounds.origin.x, y: imageSize.height - face.bounds.origin.y - face.bounds.height , width: face.bounds.width, height: face.bounds.height)
// func which detect emotion using dlib points
detectEmotionsIn(rect: actualRect, completion: { emotion in
let scaleX = UIScreen.main.bounds.width / imageSize.width
let scaleY = UIScreen.main.bounds.height / imageSize.height
let x = actualRect.origin.x * scaleX
let y = actualRect.origin.y * scaleY
let width = actualRect.width * scaleX
let height = actualRect.height * scaleY
let boundsRect = CGRect(x: x, y: y, width: width, height: height)
})
}
}
func detectEmotionsIn(rect: CGRect, completion: (String) -> ()) {
if let cgImage = image.cgImage {
let imageRef = cgImage.cropping(to: rect)
if let imageRef = imageRef {
let cropImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
let resizedImage = resizeImage(image: cropImage, newWidth: 256)
// pass resized image image to wrapper file
let points = wrapper?.doWork(onSampleBuffer: resizedImage, inRects: [NSValue(cgRect: CGRect(x: 0, y: 0, width: 256, height: 256))])
let facePointsImage = circle(radius: 2, points: points!, image: resizedImage!)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment