AVCaptureVideo没有显示标签

时间:2017-09-19 16:33:45

标签: swift uilabel avcapture coreml

我试图保留控制台中的对象以标签(classifierText)显示。 " UILabel.text的警告必须仅在主线程中使用"出现。关于为什么项目被显示为标签的问题似乎是什么?

var previewLayer: AVCaptureVideoPreviewLayer!

let classifierText: UILabel = {
    let classifier = UILabel()
    classifier.translatesAutoresizingMaskIntoConstraints = false
    classifier.textColor = .black
    classifier.font = UIFont(name: "Times-New-Roman", size: 10)
    classifier.textAlignment = .center
    return classifier
}()

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    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
    let results = finishedReq.results as?  [VNClassificationObservation]
    let firstObservation = results!.first
    self.classifierText.text = "\(firstObservation!.identifier as String)"

1 个答案:

答案 0 :(得分:1)

方法captureOutput(sampleBuffer, etc)不在主线程上运行。因此,您尝试从不是主线程的线程更改标签。

解决方案是在主线程上安排工作,如下所示:

DispatchQueue.main.async {
    self.classifierText.text = "\(firstObservation!.identifier as String)"
}