1. 简介
机器学习套件是一个移动 SDK,它通过一个强大且易用的软件包将 Google 的机器学习专业技术融入到 Android 和 iOS 应用中。无论您是刚开始接触机器学习,还是拥有丰富的相关经验,都只需几行代码即可轻松实现所需的功能。您无需具备丰富的神经网络或模型优化知识即可开始使用该套件。
运作方式
借助机器学习套件,可将 Google 的机器学习技术(如 Mobile Vision 和 TensorFlow Lite)整合到一个 SDK 中,从而使您能够轻松地在应用中运用机器学习技术。无论您是需要 Mobile Vision 设备端模型的强大实时功能,还是想要自定义 TensorFlow Lite 图片分类模型的灵活性,机器学习套件都只需几行代码即可实现。
此 Codelab 将引导您创建自己的 iOS 应用,该应用可以自动检测图片中的文字和面部特征。
构建内容
在此 Codelab 中,您将使用 机器学习套件 构建一个 iOS 应用。您的应用将:
|
|
学习内容
- 如何使用 ML Kit SDK 向任何 iOS 应用轻松添加高级机器学习功能,例如文本识别、人脸特征检测
所需条件
- 最新版 Xcode (v12.4+)
- iOS 模拟器或搭载 iOS 10.0 及更高版本的 iOS 设备
- 机器学习套件 仅支持以下两种 64 位架构:
x86_64和arm64 - 示例代码
- 具备使用 Swift 进行 iOS 开发的基础知识
- 对机器学习模型有基本的了解
此 Codelab 重点介绍机器学习套件。对于不相关的概念,我们仅会略作介绍,但是会提供相应代码块供您复制和粘贴。
2. 准备工作
下载代码
点击下面的链接可下载本 Codelab 的所有代码:
解压下载的 ZIP 文件。此操作会创建一个根文件夹 (mlkit-ios-codelab),其中包含您需要的所有资源。在此 Codelab 中,您只需要 vision 子目录中的资源。
mlkit-ios-codelab 代码库中的 vision 子目录包含两个目录:
starter - 在此 Codelab 中帮助您开始构建的起始代码。
final - 完成后的示例应用的完整代码。
使用 CocoaPods 添加机器学习套件的依赖项
CocoaPods 用于将机器学习套件依赖项添加到您的应用中。如果您尚未在自己的机器上安装 CocoaPods,请点击此处查看安装说明。安装完成后,在您喜欢的编辑器中打开 Podfile,并添加机器学习套件作为依赖项:
Podfile
platform :ios, '10.0'
use_frameworks!
pod 'GoogleMLKit/FaceDetection'
pod 'GoogleMLKit/TextRecognition'
target 'MLKit-codelab' do
end
安装机器学习套件 CocoaPod
为确保您的应用拥有所有依赖项,您应该使用命令行安装 ML Kit CocoaPod。
命令行
# Make sure you are in the root of your app
pod install
xed .
3. 运行起始应用
现在,您可以首次运行该应用了。点击 Xcode 中的
Run 以编译应用,并在 iOS 模拟器上运行该应用。
应用应在模拟器上启动。此时,您应该会看到一个基本布局,其中包含一个选择器,可让您在 2 张图片之间进行选择。在下一部分中,您将向应用添加文字识别功能,以识别图片中的文字。
4. 添加设备端文本识别功能
在此步骤中,我们会为您的应用添加功能,使其能够识别图片中的文本。
导入 MLVision 模块
确认您的 ViewController 类中存在以下导入。
ViewController.swift
import MLKit
创建 VisionTextRecognizer
向 ViewController 类添加以下延迟属性。
ViewController.swift
private lazy var textRecognizer = TextRecognizer.textRecognizer()
做好设置,并对图片进行设备端文本识别
将以下内容添加到 ViewController 类的 runTextRecognition 方法中:
ViewController.swift
func runTextRecognition(with image: UIImage) {
let visionImage = VisionImage(image: image)
textRecognizer.process(visionImage) { features, error in
self.processResult(from: features, error: error)
}
}
上述代码配置了文本识别检测器,并使用响应调用了函数 processResult(from:, error:)。
处理文本识别响应
将以下代码添加到 ViewController 类中的 processResult,以解析结果并在应用中显示结果。
ViewController.swift
func processResult(from text: Text?, error: Error?) {
removeDetectionAnnotations()
guard error == nil, let text = text else {
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
print("Text recognizer failed with error: \(errorString)")
return
}
let transform = self.transformMatrix()
// Blocks.
for block in text.blocks {
drawFrame(block.frame, in: .purple, transform: transform)
// Lines.
for line in block.lines {
drawFrame(line.frame, in: .orange, transform: transform)
// Elements.
for element in line.elements {
drawFrame(element.frame, in: .green, transform: transform)
let transformedRect = element.frame.applying(transform)
let label = UILabel(frame: transformedRect)
label.text = element.text
label.adjustsFontSizeToFitWidth = true
self.annotationOverlayView.addSubview(label)
}
}
}
}
在模拟器上运行应用
现在,在 Xcode 中点击
Run。应用加载后,确保选择器中已选中 Image 1,然后点击 Find Text 按钮。
现在,您的应用应如下图所示,其中显示了文本识别结果和叠加在原始图片上的边界框。

照片:Kai Schreiber / Wikimedia Commons / CC BY-SA 2.0
恭喜!您刚刚使用机器学习套件,向应用添加了设备端文本识别功能!设备端文本识别非常适合许多使用情形,即使应用没有网络连接也能正常运行,并且速度足够快,可用于静态图片以及实时视频帧。
5. 添加设备端人脸轮廓检测功能
在此步骤中,我们会为您的应用添加功能,使其能够检测图片中的人脸轮廓。
创建 FaceDetector
向 ViewController 类添加以下延迟属性。
ViewController.swift
private lazy var faceDetectorOption: FaceDetectorOptions = {
let option = FaceDetectorOptions()
option.contourMode = .all
option.performanceMode = .fast
return option
}()
private lazy var faceDetector = FaceDetector.faceDetector(options: faceDetectorOption)
做好设置,并对图片进行设备端面部轮廓检测
将以下内容添加到 ViewController 类的 runFaceContourDetection 方法中:
ViewController.swift
func runFaceContourDetection(with image: UIImage) {
let visionImage = VisionImage(image: image)
faceDetector.process(visionImage) { features, error in
self.processResult(from: features, error: error)
}
}
上述代码配置了文本识别检测器,并使用响应调用了函数 processResult(from:, error:)。
处理人脸检测器响应
将以下代码添加到 ViewController 类中的 processResult,以解析结果并在应用中显示结果。
ViewController.swift
func processResult(from faces: [Face]?, error: Error?) {
removeDetectionAnnotations()
guard let faces = faces else {
return
}
for feature in faces {
let transform = self.transformMatrix()
let transformedRect = feature.frame.applying(transform)
UIUtilities.addRectangle(
transformedRect,
to: self.annotationOverlayView,
color: UIColor.green
)
self.addContours(forFace: feature, transform: transform)
}
}
最后,在 ViewController 类中添加辅助方法 addContours 以绘制轮廓点。
ViewController.swift
private func addContours(forFace face: Face, transform: CGAffineTransform) {
// Face
if let faceContour = face.contour(ofType: .face) {
for point in faceContour.points {
drawPoint(point, in: .blue, transform: transform)
}
}
// Eyebrows
if let topLeftEyebrowContour = face.contour(ofType: .leftEyebrowTop) {
for point in topLeftEyebrowContour.points {
drawPoint(point, in: .orange, transform: transform)
}
}
if let bottomLeftEyebrowContour = face.contour(ofType: .leftEyebrowBottom) {
for point in bottomLeftEyebrowContour.points {
drawPoint(point, in: .orange, transform: transform)
}
}
if let topRightEyebrowContour = face.contour(ofType: .rightEyebrowTop) {
for point in topRightEyebrowContour.points {
drawPoint(point, in: .orange, transform: transform)
}
}
if let bottomRightEyebrowContour = face.contour(ofType: .rightEyebrowBottom) {
for point in bottomRightEyebrowContour.points {
drawPoint(point, in: .orange, transform: transform)
}
}
// Eyes
if let leftEyeContour = face.contour(ofType: .leftEye) {
for point in leftEyeContour.points {
drawPoint(point, in: .cyan, transform: transform)
}
}
if let rightEyeContour = face.contour(ofType: .rightEye) {
for point in rightEyeContour.points {
drawPoint(point, in: .cyan, transform: transform)
}
}
// Lips
if let topUpperLipContour = face.contour(ofType: .upperLipTop) {
for point in topUpperLipContour.points {
drawPoint(point, in: .red, transform: transform)
}
}
if let bottomUpperLipContour = face.contour(ofType: .upperLipBottom) {
for point in bottomUpperLipContour.points {
drawPoint(point, in: .red, transform: transform)
}
}
if let topLowerLipContour = face.contour(ofType: .lowerLipTop) {
for point in topLowerLipContour.points {
drawPoint(point, in: .red, transform: transform)
}
}
if let bottomLowerLipContour = face.contour(ofType: .lowerLipBottom) {
for point in bottomLowerLipContour.points {
drawPoint(point, in: .red, transform: transform)
}
}
// Nose
if let noseBridgeContour = face.contour(ofType: .noseBridge) {
for point in noseBridgeContour.points {
drawPoint(point, in: .yellow, transform: transform)
}
}
if let noseBottomContour = face.contour(ofType: .noseBottom) {
for point in noseBottomContour.points {
drawPoint(point, in: .yellow, transform: transform)
}
}
}
在模拟器上运行应用
现在,在 Xcode 中点击
Run。应用加载后,确保选择器中已选中 Image 2,然后点击 Find Face Contour 按钮。您的应用现在应如下图所示,其中显示了 Grace Hopper 面部的轮廓,这些轮廓以点的形式叠加在原始图片之上。

恭喜!您刚刚使用设备端机器学习套件向应用添加了设备端人脸轮廓检测功能。设备端人脸轮廓检测功能非常适合许多使用情形,即使应用没有网络连接也能正常运行,并且速度足够快,可用于静态图片以及实时视频帧。
6. 恭喜!
您已使用机器学习套件轻松为应用添加了高级机器学习功能。
所学内容
- 如何将机器学习套件添加到 iOS 应用
- 如何使用机器学习套件的设备端文本识别功能来查找图像中的文本
- 如何使用机器学习套件的设备端人脸识别功能来识别图片中的面部特征
后续步骤
- 在您自己的 iOS 应用中使用机器学习套件。
了解详情
- https://g.co/mlkit

