今年的WWDC上,關於人工智能方面Apple開放了CoreML工具包。
今天就趁着時間還早果斷的嘗試了一下到底有多容易。
import UIKit
import CoreML
import Vision
首先頭文件里CoreML和Vision兩個新的包都需要引入。
如果只是模仿Apple官方給出的模型可以不使用Vision包,但是如果要做圖片識別那么最好使用Vision的方法。(原因之后會提到)
@IBAction func openLibrary(_ sender: Any) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary; imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imagePicked.contentMode = .scaleToFill imagePicked.image = pickedImage } picker.dismiss(animated: true, completion: nil) }
簡單的導入圖片過程,在此不做解釋。
@IBAction func saveImage(_ sender: Any) { let imageData = imagePicked.image?.cgImage let model = try! VNCoreMLModel(for: Resnet50().model) let request = VNCoreMLRequest(model: model, completionHandler: myResultsMethod) let handler = VNImageRequestHandler(cgImage: imageData!) try! handler.perform([request]) }
let model = try! VNCoreMLModel(for: Resnet50().model)//1
這是一個選擇模型個的方法,模型我直接選用的Apple推薦的Resnet50()。(其實有了第三方模型轉換之后自己編譯也很簡單)
let handler = VNImageRequestHandler(cgImage: imageData!)//2
將文件轉換成模型識別可支持的數據類型(CVPixelBuffer)當然也有別的可轉換方法,但是直接使用Vision的方法更容易實現。
let request = VNCoreMLRequest(model: model, completionHandler: myResultsMethod)//3
讀取模型並返回結果至myResultsMethod方法中。
guard let results = request.results as? [VNClassificationObservation]//4
返回結果存儲在results中(數組型數據)
for classification in results { print(classification.identifier, // the scene label classification.confidence) }
至此一個帶有人工智能的App就開發完了。
准確來說不到十行代碼。