Skip to content

Instantly share code, notes, and snippets.

@anupamchugh
Last active October 15, 2019 07:14
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 anupamchugh/3691ce07979dc1836030e8a3ce212864 to your computer and use it in GitHub Desktop.
Save anupamchugh/3691ce07979dc1836030e8a3ce212864 to your computer and use it in GitHub Desktop.
func drawRectanglesOnObservations(observations : [VNDetectedObjectObservation]){
DispatchQueue.main.async {
guard let image = self.imageView.image
else{
print("Failure in retrieving image")
return
}
let imageSize = image.size
var imageTransform = CGAffineTransform.identity.scaledBy(x: 1, y: -1).translatedBy(x: 0, y: -imageSize.height)
imageTransform = imageTransform.scaledBy(x: imageSize.width, y: imageSize.height)
UIGraphicsBeginImageContextWithOptions(imageSize, true, 0)
let graphicsContext = UIGraphicsGetCurrentContext()
image.draw(in: CGRect(origin: .zero, size: imageSize))
graphicsContext?.saveGState()
graphicsContext?.setLineJoin(.round)
graphicsContext?.setLineWidth(8.0)
graphicsContext?.setFillColor(red: 0, green: 1, blue: 0, alpha: 0.3)
graphicsContext?.setStrokeColor(UIColor.green.cgColor)
var previousString = ""
let elements = ["VISION","COREML"]
observations.forEach { (observation) in
var string = observationStringLookup[observation as! VNTextObservation] ?? ""
let tempString = string
string = string.replacingOccurrences(of: previousString, with: "")
string = string.trim()
previousString = tempString
if elements.contains(where: string.contains){
let observationBounds = observation.boundingBox.applying(imageTransform)
graphicsContext?.addRect(observationBounds)
}
}
graphicsContext?.drawPath(using: CGPathDrawingMode.fillStroke)
graphicsContext?.restoreGState()
let drawnImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.imageView.image = drawnImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment