小驴拉磨之人工智能-CoreML处理图像

首先导入头文件

import CoreML
//图像识别框架。
import Vision

功能实现

func startIdentifyingPictures() {
        //拖入素材,拿到图片URL
        let path = Bundle.main.path(forResource: "111", ofType: "png")
        let imageUrl = NSURL.fileURL(withPath: path!)
        //拿到模型文件
        let fileModel = Resnet50()//GoogLeNetPlaces()
        // 把模型拿來做视觉处理
        let model = try! VNCoreMLModel(for: fileModel.model)
        //创建识别图片的请求头
        let handler = VNImageRequestHandler(url: imageUrl)
        //创建请求,completionHandler请求回调
        let request = VNCoreMLRequest(model: model) { (request, error) in
            //拿到识别结果
            //1、判别结果是否存在
            guard let results = request.results as? [VNClassificationObservation] else {
                fatalError("识别结果为空")
            }
            //什么东西
            var bestPrediction = ""
            //相似度
            var bestConfidence: VNConfidence = 0
            //for遍历results
            for classfication in results {
                if classfication.confidence > bestConfidence {
                    bestPrediction = classfication.identifier
                    bestConfidence = classfication.confidence
                }
                //print("預測結果\(classfication.identifier) 可信度\(classfication.confidence)")
            }
            print("最終預測結果\(bestPrediction) 可信度\(bestConfidence)")
        }
        try! handler.perform([request])
    }

小编送上Dome地址:https://github.com/dongdongca/CoreML

注意:因为模型包比较大,项目上传没有添加,下载的时候请自行下载对应的模型拖入项目,下载地址:https://developer.apple.com/machine-learning

你可能感兴趣的:(小驴拉磨之人工智能-CoreML处理图像)