Guest User

Untitled

a guest
Aug 15th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. func displayRect(for observation: VNRectangleObservation) {
  2. DispatchQueue.main.async { [weak self] in
  3. guard let size = self?.imageView.frame.size else { return }
  4. guard let origin = self?.imageView.frame.origin else { return }
  5.  
  6. let transform = CGAffineTransform(scaleX: size.width, y: size.height)
  7.  
  8. let rect = observation.boundingBox.applying(transform)
  9. .applying(CGAffineTransform(scaleX: 1.0, y: -1.0))
  10. .applying(CGAffineTransform(translationX: 0.0, y: size.height))
  11. .applying(CGAffineTransform(translationX: -origin.x, y: -origin.y))
  12.  
  13. let path = UIBezierPath(rect: rect)
  14.  
  15. let layer = CAShapeLayer()
  16. layer.path = path.cgPath
  17. layer.fillRule = kCAFillRuleEvenOdd
  18. layer.fillColor = UIColor.red.withAlphaComponent(0.2).cgColor
  19.  
  20. self?.overlay.sublayers = nil
  21. self?.overlay.addSublayer(layer)
  22. }
  23. }
  24.  
  25. func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
  26. guard let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
  27.  
  28. // Also tried converting to CGImage, creating handler from that, but made no difference
  29. let handler = VNImageRequestHandler(cvPixelBuffer: buffer, options: [:])
  30.  
  31. let request = VNDetectRectanglesRequest()
  32. request.minimumAspectRatio = VNAspectRatio(0.2)
  33. request.maximumAspectRatio = VNAspectRatio(1.0)
  34. request.minimumSize = Float(0.3)
  35.  
  36. try? handler.perform([request])
  37.  
  38. // Note: Only ever captures one rectangle, so calling `first` not the issue.
  39. guard let observations = request.results as? [VNRectangleObservation],
  40. let observation = observations.first else {
  41. return removeShapeLayer()
  42. }
  43.  
  44. displayRect(for: observation, buffer: buffer)
  45. }
Add Comment
Please, Sign In to add comment