Skip to content

Instantly share code, notes, and snippets.

@iosdevie
Created May 29, 2021 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iosdevie/07346635dc6ea39c11dd1fb30f18c74f to your computer and use it in GitHub Desktop.
Save iosdevie/07346635dc6ea39c11dd1fb30f18c74f to your computer and use it in GitHub Desktop.
private let workQueue = DispatchQueue(label: "VisionRequest", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem)
private func processImage(_ image: UIImage) {
guard let originalImage = image.cgImage else { return }
workQueue.async {
let requestHandler = VNImageRequestHandler(cgImage: originalImage, options: [:])
do {
try requestHandler.perform([self.saliencyRequest])
guard let results = self.saliencyRequest.results?.first
else{return}
if let observation = results as? VNSaliencyImageObservation
{
var unionOfSalientRegions = CGRect(x: 0, y: 0, width: 0, height: 0)
let salientObjects = observation.salientObjects
let showAlert = (salientObjects?.isEmpty ?? false)
for salientObject in salientObjects ?? [] {
unionOfSalientRegions = unionOfSalientRegions.union(salientObject.boundingBox)
}
if let ciimage = CIImage(image: image)
{
let salientRect = VNImageRectForNormalizedRect(unionOfSalientRegions,
Int(ciimage.extent.size.width),
Int(ciimage.extent.size.height))
let croppedImage = ciimage.cropped(to: salientRect)
let thumbnail = UIImage(ciImage:croppedImage)
DispatchQueue.main.async {
if showAlert{
let alertController = UIAlertController(title: "Oops!", message: "No highlights were found", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: { _ in
}))
self.present(alertController, animated: false, completion: nil)
}
self.imageView?.image = thumbnail
}
}
}
} catch {
print(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment