Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
- guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
- return
- }
- var requestOptions: [VNImageOption: Any] = [:]
- if let camData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) {
- requestOptions = [.cameraIntrinsics: camData]
- }
- let imageOrientation = self.videoLayer.connection!.videoOrientation.imageOrientation()
- let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: imageOrientation, options: requestOptions)
- DispatchQueue.global(qos: .userInitiated).async {
- do {
- try imageRequestHandler.perform([self.rectanglesRequest])
- } catch {
- print(error)
- }
- }
- }
- func detectRectanglesHandler(request: VNRequest, error: Error?) {
- guard let observations = request.results else {
- print("no result")
- return
- }
- let result = observations.map({ $0 as? VNRectangleObservation })
- for region in result {
- guard let rg = region else {
- continue
- }
- let obs: VNRectangleObservation = rg
- let rectanglesTransform = CGAffineTransform.identity.scaledBy(x: frameSize.width, y: frameSize.height)
- let topLeft = obs.topLeft.applying(rectanglesTransform)
- let topRight = obs.topRight.applying(rectanglesTransform)
- let bottomLeft = obs.bottomLeft.applying(rectanglesTransform)
- let bottomRight = obs.bottomRight.applying(rectanglesTransform)
- if drawingSemaphore.wait(timeout: .now()) == .success {
- let uiTransform = CGAffineTransform.identity.scaledBy(x: 1, y: -1).translatedBy(x: 0.0, y: -frameSize.height)
- let boundingBox = obs.boundingBox.applying(rectanglesTransform)
- DispatchQueue.main.async {
- guard self.cameraView.frame.contains(boundingBox) else {
- print("invalid detected rectangle");
- self.drawingSemaphore.signal()
- return
- }
- let path = UIBezierPath()
- path.move(to: topLeft.applying(uiTransform))
- path.addLine(to: topRight.applying(uiTransform))
- path.addLine(to: bottomRight.applying(uiTransform))
- path.addLine(to: bottomLeft.applying(uiTransform))
- path.close()
- self.regionOfInterest?.removeFromSuperlayer()
- let regionOfInterest = CAShapeLayer()
- regionOfInterest.path = path.cgPath
- regionOfInterest.fillColor = UIColor.clear.cgColor
- regionOfInterest.strokeColor = UIColor.white.cgColor
- regionOfInterest.zPosition = -2
- self.cameraView.layer.addSublayer(regionOfInterest)
- self.regionOfInterest = regionOfInterest
- self.drawingSemaphore.signal()
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment