Skip to content

Instantly share code, notes, and snippets.

@eilonkr
Created May 13, 2022 21:31
Show Gist options
  • Save eilonkr/4128fd8afb9ae285161f9ccc48920fbc to your computer and use it in GitHub Desktop.
Save eilonkr/4128fd8afb9ae285161f9ccc48920fbc to your computer and use it in GitHub Desktop.
func getFaceRects(in image: UIImage, normalizedTo rect: CGRect) -> [CGRect] {
guard var ciImage = CIImage(image: image) else {
print("Couldn't create CIImage.")
return []
}
// correct the orientation becuase `CIImage.init` can lose it
ciImage = ciImage.oriented(.init(image.imageOrientation))
let scaleFactorX = rect.width / ciImage.extent.width
let scaleFactorY = rect.height / ciImage.extent.height
var normalizedRects: [CGRect] = []
// request the results from our detector
for faceFeature in ciDetector.features(in: ciImage) {
// every `CIFeature` has a `bounds` property, which is relative to the image dimensions.
// keep in mind that we work here in CoreImage's coordinate system, meaning that the origin
// is bottom left, instead of UIKit's top left.
let faceRect = faceFeature.bounds
// normalize the face feature bounds to the given rect
let normalizedRect = CGRect(x: faceRect.minX * scaleFactorX,
y: rect.height - (faceRect.maxY * scaleFactorY),
width: faceRect.width * scaleFactorX,
height: faceRect.height * scaleFactorY)
normalizedRects.append(normalizedRect)
}
return normalizedRects
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment