UILabel.text必须仅在主线程中使用

时间:2017-09-27 16:59:42

标签: ios iphone swift xcode coreml

我正在尝试将第一个观察结果打印在outputLabel中,但我遇到了问题。谢谢你的帮助。

导入UIKit 导入AVKit 进口愿景

类ViewController:UIViewController,AVCaptureVideoDataOutputSampleBufferDelegate {

@IBOutlet weak var outputLabel: UILabel!



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //camera start up
    let captureSession = AVCaptureSession()
    captureSession.sessionPreset = .photo

    guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
    guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
    captureSession.addInput(input)

    captureSession.startRunning()

    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    view.layer.addSublayer(previewLayer)
    previewLayer.frame = view.frame

    let dataOutput = AVCaptureVideoDataOutput()
    dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
    captureSession.addOutput(dataOutput)


    //VNImageRequestHandler(cgImage: CGImage, options: [:]).perform(<#T##requests: [VNRequest]##[VNRequest]#>)



}

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

    //print("Camera was able to capture a frame", Date())

    guard let pixelBuffer: CVPixelBuffer =  CMSampleBufferGetImageBuffer(sampleBuffer) else { return }

    guard let model = try? VNCoreMLModel(for: Resnet50().model) else { return }

    let request = VNCoreMLRequest(model: model)
   { (finishedReq, err) in

    //check errors

    //print(finishedReq.results)
    guard let results = finishedReq.results as? [VNClassificationObservation] else { return }

    guard let firstObservation = results.first else { return }
    print(firstObservation.identifier, firstObservation.confidence)

    self.outputLabel.text = String(describing: firstObservation)


    }

    try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])


}

}

0 个答案:

没有答案