我想将firstObservastion.identifier
和firstObservastion.confidence
放入UILabel。
我可以将print
变量作为字符串添加到输出中,并使用以下行:print("Guess: \(firstObservastion.identifier) Certainty: \(firstObservastion.confidence)%")
,但是我无法将这些字符串变量移至创建它们的本地函数之外的任何位置(以放置将该字符串转换为uilabel)。我似乎也无法做出return声明。
self.stringy = "Guess: \(firstObservastion.identifier) Certainty: \(firstObservastion.confidence)%"
似乎无能为力。
这是项目的完整代码:
import UIKit
import AVKit
import Vision
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//here we start the camera
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)
// let request = VNCoreMLModel(model: VNCoreMLModel, completionHandler: VNRequestCompletionHandler)
// VNImageRequestHandler(cgImage: <#T##CGImage#>, options: <#T##[VNImageOption : Any]#>)
self.Labele.text = stringy
}
var stringy:String!
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
//print(finishedReq.results)
guard let results = finishedReq.results as? [VNClassificationObservation] else {return}
guard let firstObservastion = results.first else {return}
print("Guess: \(firstObservastion.identifier) Certainty: \(firstObservastion.confidence)%")
self.stringy = "Guess: \(firstObservastion.identifier) Certainty: \(firstObservastion.confidence)%"
}
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
}
@IBOutlet weak var Labele: UILabel!
}