swift开发笔记28 CoreML

{

  func detectScene(image: CIImage) {

    answerLabel.text = "detecting scene..."

    

    // Load the ML model through its generated class

    guard let model = try? VNCoreMLModel(for: GoogLeNetPlaces().model) else {

      fatalError("can't load Places ML model")

    }

    

    // Define a Vision request service with the ML model

    let request = VNCoreMLRequest(model: model) { [weak self] request, error in

      guard let results = request.results,

        let topResult = results.first as? VNClassificationObservation else {

          fatalError("unexpected result type from VNCoreMLRequest")

      }

      

      // Update UI on main queue

      let article = (["a", "e", "i", "o", "u"].contains(topResult.identifier.first!)) ? "an" : "a"

      

      DispatchQueue.main.async { [weak self] in

        self?.answerLabel.text = "(Int(topResult.confidence * 100))% it's (article) (topResult.identifier)"

      }

    }

    

    // Create a request handler with the image provided

    let handler = VNImageRequestHandler(ciImage: image)

    

    // Perform the request service with the request handler

    DispatchQueue.global(qos: .userInteractive).async {

      do {

        try handler.perform([request])

      } catch {

        print(error)

      }

    }

  }

}

原文地址:https://www.cnblogs.com/dengchaojie/p/8215673.html