iOS Core ML 机器学习入门

2020-01-04  本文已影响0人  七里田间的守望者

前言
机器学习的分类:

开始构建代码

class ViewController: UIViewController {

    
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func pickImage(_ sender: Any) {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .camera
        present(picker, animated: true, completion: nil)
    }
    
}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
            imageView.image = image // 展示拍摄的图片
        }
        picker.dismiss(animated: true, completion: nil)
    }
}
import Vision
import CoreML

然后 转化modle VNCoreMLModel(for: MobileNetV2Int8LUT())

//1.转化图像
guard let ciImage = CIImage(image: image) else{
    fatalError("不能把图像转化为CIImage")
}

//2.加载MLModel(训练好的模型),并做了一个让MLModel识别图像的请求
guard let model = try? VNCoreMLModel(for: Inceptionv3().model) else{
    fatalError("加载MLmodel失败")
}
//模型请求
let request = VNCoreMLRequest(model: model) { (request, error) in
    //图像识别结果--output
    guard let res = request.results else{
        print("图像识别失败")
        return
    }
    let classifications = res as! [VNClassificationObservation]
    if classifications.isEmpty{
        print("不知道是什么")
    }else{
      print("识别结果\(classifications.first!.identifier)")
    }
}
//把要识别的图片转化为正方形 (因为这个模型要求图片最好是正方形的)
request.imageCropAndScaleOption = .centerCrop

//执行这个请求--input进需要识别的图像
do{
   try VNImageRequestHandler(ciImage: ciImage).perform([request])
}catch{
    print("执行图片识别请求失败,原因是:\(error.localizedDescription)")
}

安装 coremltools
这个工具主要就是为了转化第三方的训练数据转化为iOS需要的mlmodel

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install -U coremltools

ps: 如果是pip3 就使用pip3

开始转化模型
主要就是使用coremltools

coremltools详细的用法

import coremltools

# Convert a Caffe model to a classifier in Core ML
# bvlc_alexnet 要转化的模型
# deploy.prototxt 输入
# class_labels 输出
coreml_model = coremltools.converters.caffe.convert(
    ('bvlc_alexnet.caffemodel', 'deploy.prototxt'),image_input_names='data', class_labels='class_labels.txt'
)

# Now save the model
coreml_model.save('BVLCObjectClassifier.mlmodel')

至此python训练的模型就成功的转化为coreml模型了,注意在使用coremltools的过程中,要看相关的操作文档

如何制作一个图像识别的 CoreML

然后 用 xcode 新建 playground

import CreateMLUI
MLImageClassifierBuilder().showInLiveView()

就会在右侧显示制作模型的界面,把要训练的数据直接拖进去开始训练。然后保存模型即可。

上一篇 下一篇

猜你喜欢

热点阅读