Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jacobsapps/fda4601f873d5b83442f8dd2c235c662 to your computer and use it in GitHub Desktop.
Save jacobsapps/fda4601f873d5b83442f8dd2c235c662 to your computer and use it in GitHub Desktop.
private func generateCutout(image: UIImage) throws -> UIImage? {
guard let cgImage = image.cgImage else { return nil }
let inputImage = CIImage(cgImage: cgImage, options: [.applyOrientationProperty: true])
let request = VNGenerateForegroundInstanceMaskRequest()
let handler = VNImageRequestHandler(ciImage: inputImage)
try handler.perform([request])
guard let observation = request.results?.first else {
return nil
}
let pixelBuffer = try observation.generateMaskedImage(
ofInstances: observation.allInstances,
from: handler,
croppedToInstancesExtent: false
)
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
let context = CIContext()
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else {
return nil
}
return UIImage(cgImage: cgImage)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment