Created
May 29, 2021 18:54
-
-
Save iosdevie/07346635dc6ea39c11dd1fb30f18c74f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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