文章目录
前言
使用DeepLabV3图像分割模型在iOS应用程序中添加、删除和修改图像背景
Core ML是Apple的移动机器学习框架,允许在设备上部署、运行和重新训练模型。
作为第一次学习使用人像识别并实现机器学习的最流行用例之一:iOS应用程序图像分割
一、获取DeepLab Core ML模型
1.Core ML模型
在Apple Developer上可义获取Create ML以及对Core ML的概述、讲解及其的转换器和已训练好的模型,可以更多了解其技术。
2.导入Core ML
以Swift作为用户界面启动一个新的Xcode项目,并拖放已下载好的Core ML文件
二、人脸识别
1.读取相册,导入图片
@IBAction func getImage(_ sender: UIButton) {
let actionSheetController = UIAlertController()
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel){
(alertAction)-> Void in
print("Tap 取消 Button")
}
let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive){
(alertAction) -> Void in
self.getImageGo(type:1)
}
let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default){
(alertAction)-> Void in
self.getImageGo(type:2)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(takingPicturesAction)
actionSheetController.addAction(photoAlbumAction)
self.present(actionSheetController, animated: true,completion:nil)
}
点击相册可读取导入图片,拍照可在真机iPhone上实现,Simulator无法实现
2.识别图片是否有人像,没有提示无法识别
func detect(){
let person = CIImage(cgImage: image.image!.cgImage!)
let accuracy = [CIDetectorAccuracy:CIDetectorAccuracyHigh]
let facedetector = CIDetector(ofType: CIDetectorTypeFace, context: nil,options: accuracy)
let faces = facedetector?.features(in: person)
if faces?.first is CIFaceFeature {
print("检测到人脸!")
}else{
let alert = UIAlertController(title: "提示", message: "未检测到人脸", preferredStyle:.alert)
let alertAction = UIAlertAction(title: "确定", style:.default,handler: nil)
alert.addAction(alertAction)
self.present(alert, animated: true,completion: nil)
}
}
func getImageGo(type:Int){
takingPicture = UIImagePickerController.init()
if(type==1){
takingPicture.sourceType = .camera
}else if(type==2){
takingPicture.sourceType = .photoLibrary
}
//是否截取,设置为true在获取图片后可以将其截取成正