在 iOS 上使用機器學習套件辨識數位墨水

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

您可以透過 ML Kit 的數位墨水辨識功能,辨識數百種語言在數位表面上手寫的文字,還可以對草圖分類。

立即體驗

事前準備

  1. 在 Podfile 中加入下列機器學習套件程式庫:

    pod 'GoogleMLKit/DigitalInkRecognition', '3.2.0'
    
    
  2. 安裝或更新專案的 Pod 後,使用 .xcworkspace 開啟 Xcode 專案。Xcode 13.2.1 以上版本支援機器學習套件。

您現在可以開始辨識 Ink 物件中的文字。

建構 Ink 物件

建構 Ink 物件的主要方法是在觸控螢幕上繪圖。在 iOS 裝置上,您可以使用 UIImageView觸控事件處理常式,藉此繪製螢幕上的筆觸,以及儲存筆劃點以建構 Ink 物件。下列程式碼片段將說明這個一般模式。如需更完整的觸控事件處理、螢幕畫面繪圖和筆劃資料管理等功能的範例,請參閱快速入門導覽課程應用程式

Swift

@IBOutlet weak var mainImageView: UIImageView!
var kMillisecondsPerTimeInterval = 1000.0
var lastPoint = CGPoint.zero
private var strokes: [Stroke] = []
private var points: [StrokePoint] = []

func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
  UIGraphicsBeginImageContext(view.frame.size)
  guard let context = UIGraphicsGetCurrentContext() else {
    return
  }
  mainImageView.image?.draw(in: view.bounds)
  context.move(to: fromPoint)
  context.addLine(to: toPoint)
  context.setLineCap(.round)
  context.setBlendMode(.normal)
  context.setLineWidth(10.0)
  context.setStrokeColor(UIColor.white.cgColor)
  context.strokePath()
  mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
  mainImageView.alpha = 1.0
  UIGraphicsEndImageContext()
}

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
  guard let touch = touches.first else {
    return
  }
  lastPoint = touch.location(in: mainImageView)
  let t = touch.timestamp
  points = [StrokePoint.init(x: Float(lastPoint.x),
                             y: Float(lastPoint.y),
                             t: Int(t * kMillisecondsPerTimeInterval))]
  drawLine(from:lastPoint, to:lastPoint)
}

override func touchesMoved(_ touches: Set, with event: UIEvent?) {
  guard let touch = touches.first else {
    return
  }
  let currentPoint = touch.location(in: mainImageView)
  let t = touch.timestamp
  points.append(StrokePoint.init(x: Float(currentPoint.x),
                                 y: Float(currentPoint.y),
                                 t: Int(t * kMillisecondsPerTimeInterval)))
  drawLine(from: lastPoint, to: currentPoint)
  lastPoint = currentPoint
}

override func touchesEnded(_ touches: Set, with event: UIEvent?) {
  guard let touch = touches.first else {
    return
  }
  let currentPoint = touch.location(in: mainImageView)
  let t = touch.timestamp
  points.append(StrokePoint.init(x: Float(currentPoint.x),
                                 y: Float(currentPoint.y),
                                 t: Int(t * kMillisecondsPerTimeInterval)))
  drawLine(from: lastPoint, to: currentPoint)
  lastPoint = currentPoint
  strokes.append(Stroke.init(points: points))
  self.points = []
  doRecognition()
}

Objective-C

// Interface
@property (weak, nonatomic) IBOutlet UIImageView *mainImageView;
@property(nonatomic) CGPoint lastPoint;
@property(nonatomic) NSMutableArray *strokes;
@property(nonatomic) NSMutableArray *points;

// Implementations
static const double kMillisecondsPerTimeInterval = 1000.0;

- (void)drawLineFrom:(CGPoint)fromPoint to:(CGPoint)toPoint {
  UIGraphicsBeginImageContext(self.mainImageView.frame.size);
  [self.mainImageView.image drawInRect:CGRectMake(0, 0, self.mainImageView.frame.size.width,
                                                  self.mainImageView.frame.size.height)];
  CGContextMoveToPoint(UIGraphicsGetCurrentContext(), fromPoint.x, fromPoint.y);
  CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), toPoint.x, toPoint.y);
  CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
  CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 10.0);
  CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1, 1, 1, 1);
  CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeNormal);
  CGContextStrokePath(UIGraphicsGetCurrentContext());
  CGContextFlush(UIGraphicsGetCurrentContext());
  self.mainImageView.image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
}

- (void)touchesBegan:(NSSet *)touches withEvent:(nullable UIEvent *)event {
  UITouch *touch = [touches anyObject];
  self.lastPoint = [touch locationInView:self.mainImageView];
  NSTimeInterval time = [touch timestamp];
  self.points = [NSMutableArray array];
  [self.points addObject:[[MLKStrokePoint alloc] initWithX:self.lastPoint.x
                                                         y:self.lastPoint.y
                                                         t:time * kMillisecondsPerTimeInterval]];
  [self drawLineFrom:self.lastPoint to:self.lastPoint];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(nullable UIEvent *)event {
  UITouch *touch = [touches anyObject];
  CGPoint currentPoint = [touch locationInView:self.mainImageView];
  NSTimeInterval time = [touch timestamp];
  [self.points addObject:[[MLKStrokePoint alloc] initWithX:currentPoint.x
                                                         y:currentPoint.y
                                                         t:time * kMillisecondsPerTimeInterval]];
  [self drawLineFrom:self.lastPoint to:currentPoint];
  self.lastPoint = currentPoint;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(nullable UIEvent *)event {
  UITouch *touch = [touches anyObject];
  CGPoint currentPoint = [touch locationInView:self.mainImageView];
  NSTimeInterval time = [touch timestamp];
  [self.points addObject:[[MLKStrokePoint alloc] initWithX:currentPoint.x
                                                         y:currentPoint.y
                                                         t:time * kMillisecondsPerTimeInterval]];
  [self drawLineFrom:self.lastPoint to:currentPoint];
  self.lastPoint = currentPoint;
  if (self.strokes == nil) {
    self.strokes = [NSMutableArray array];
  }
  [self.strokes addObject:[[MLKStroke alloc] initWithPoints:self.points]];
  self.points = nil;
  [self doRecognition];
}

請注意,程式碼片段包含範例函式,可將筆劃繪製至 UIImageView 中,應根據應用程式進行調整。建議您在繪製線段時使用圓頂,讓零長度的片段被繪製為點 (請想以小寫字母 i 為點)。每個筆劃寫入完畢之後,系統都會呼叫 doRecognition() 函式,並將於下方定義。

取得 DigitalInkRecognizer 的執行個體

如要執行辨識,我們必須將 Ink 物件傳遞至 DigitalInkRecognizer 執行個體。如要取得 DigitalInkRecognizer 執行個體,我們必須先下載所需語言的辨識器模型,並將模型載入 RAM。您可以使用以下程式碼片段完成這項作業。為求簡化,請將程式碼片段放在 viewDidLoad() 方法中,並使用硬式編碼的語言名稱。請參閱快速入門導覽課程應用程式的範例,瞭解如何向使用者顯示可用的語言清單及下載所選語言。

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let languageTag = "en-US"
  let identifier = DigitalInkRecognitionModelIdentifier(forLanguageTag: languageTag)
  if identifier == nil {
    // no model was found or the language tag couldn't be parsed, handle error.
  }
  let model = DigitalInkRecognitionModel.init(modelIdentifier: identifier!)
  let modelManager = ModelManager.modelManager()
  let conditions = ModelDownloadConditions.init(allowsCellularAccess: true,
                                         allowsBackgroundDownloading: true)
  modelManager.download(model, conditions: conditions)
  // Get a recognizer for the language
  let options: DigitalInkRecognizerOptions = DigitalInkRecognizerOptions.init(model: model)
  recognizer = DigitalInkRecognizer.digitalInkRecognizer(options: options)
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  NSString *languagetag = @"en-US";
  MLKDigitalInkRecognitionModelIdentifier *identifier =
      [MLKDigitalInkRecognitionModelIdentifier modelIdentifierForLanguageTag:languagetag];
  if (identifier == nil) {
    // no model was found or the language tag couldn't be parsed, handle error.
  }
  MLKDigitalInkRecognitionModel *model = [[MLKDigitalInkRecognitionModel alloc]
                                          initWithModelIdentifier:identifier];
  MLKModelManager *modelManager = [MLKModelManager modelManager];
  [modelManager downloadModel:model conditions:[[MLKModelDownloadConditions alloc]
                                                initWithAllowsCellularAccess:YES
                                                allowsBackgroundDownloading:YES]];
  MLKDigitalInkRecognizerOptions *options =
      [[MLKDigitalInkRecognizerOptions alloc] initWithModel:model];
  self.recognizer = [MLKDigitalInkRecognizer digitalInkRecognizerWithOptions:options];
}

快速入門導覽課程應用程式提供額外的程式碼,說明如何同時處理多個下載,以及如何透過處理完成通知來判斷下載成功。

辨識 Ink 物件

接下來是 doRecognition() 函式,為了方便起見,我們會從 touchesEnded() 呼叫該函式。在其他應用程式中,可能只有逾時後或使用者按下按鈕觸發辨識時,才會叫用辨識。

Swift

func doRecognition() {
  let ink = Ink.init(strokes: strokes)
  recognizer.recognize(
    ink: ink,
    completion: {
      [unowned self]
      (result: DigitalInkRecognitionResult?, error: Error?) in
      var alertTitle = ""
      var alertText = ""
      if let result = result, let candidate = result.candidates.first {
        alertTitle = "I recognized this:"
        alertText = candidate.text
      } else {
        alertTitle = "I hit an error:"
        alertText = error!.localizedDescription
      }
      let alert = UIAlertController(title: alertTitle,
                                  message: alertText,
                           preferredStyle: UIAlertController.Style.alert)
      alert.addAction(UIAlertAction(title: "OK",
                                    style: UIAlertAction.Style.default,
                                  handler: nil))
      self.present(alert, animated: true, completion: nil)
    }
  )
}

Objective-C

- (void)doRecognition {
  MLKInk *ink = [[MLKInk alloc] initWithStrokes:self.strokes];
  __weak typeof(self) weakSelf = self;
  [self.recognizer
      recognizeInk:ink
        completion:^(MLKDigitalInkRecognitionResult *_Nullable result,
                     NSError *_Nullable error) {
    typeof(weakSelf) strongSelf = weakSelf;
    if (strongSelf == nil) {
      return;
    }
    NSString *alertTitle = nil;
    NSString *alertText = nil;
    if (result.candidates.count > 0) {
      alertTitle = @"I recognized this:";
      alertText = result.candidates[0].text;
    } else {
      alertTitle = @"I hit an error:";
      alertText = [error localizedDescription];
    }
    UIAlertController *alert =
        [UIAlertController alertControllerWithTitle:alertTitle
                                            message:alertText
                                     preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK"
                                              style:UIAlertActionStyleDefault
                                            handler:nil]];
    [strongSelf presentViewController:alert animated:YES completion:nil];
  }];
}

管理模型下載

我們已經知道如何下載辨識模型。下列程式碼片段說明如何檢查是否已下載模型,或者在不再需要儲存空間時刪除模型。

檢查是否已下載模型

Swift

let model : DigitalInkRecognitionModel = ...
let modelManager = ModelManager.modelManager()
modelManager.isModelDownloaded(model)

Objective-C

MLKDigitalInkRecognitionModel *model = ...;
MLKModelManager *modelManager = [MLKModelManager modelManager];
[modelManager isModelDownloaded:model];

刪除已下載的模型

Swift

let model : DigitalInkRecognitionModel = ...
let modelManager = ModelManager.modelManager()

if modelManager.isModelDownloaded(model) {
  modelManager.deleteDownloadedModel(
    model!,
    completion: {
      error in
      if error != nil {
        // Handle error
        return
      }
      NSLog(@"Model deleted.");
    })
}

Objective-C

MLKDigitalInkRecognitionModel *model = ...;
MLKModelManager *modelManager = [MLKModelManager modelManager];

if ([self.modelManager isModelDownloaded:model]) {
  [self.modelManager deleteDownloadedModel:model
                                completion:^(NSError *_Nullable error) {
                                  if (error) {
                                    // Handle error.
                                    return;
                                  }
                                  NSLog(@"Model deleted.");
                                }];
}

改善文字辨識準確度的訣竅

文字辨識的準確度可能因語言而異。準確率也取決於寫入樣式。雖然 Digital Ink Recognition 經過訓練,可處理各種類型的寫入樣式,但結果可能因使用者而異。

以下提供一些方法,可協助提高文字辨識器的準確度。請注意,這些技巧不適用於表情符號、自動繪圖及形狀的繪圖分類器。

書寫區域

許多應用程式都有使用者定義的寫入區域。符號的含義部分取決於其大小與包含該符號的寫入區域大小相比。例如,小寫英文字母「o」或「c」與半形逗號與正斜線的差異。

告訴辨識器寫入區域的寬度和高度,可以提高準確度。不過,辨識器會假設寫入區域只包含一行文字。如果實體寫入區域夠大,且使用者能夠編寫兩行或更多行,您可以傳入 WriteArea,其高度是您單行文字的高度估計值,進而獲得更好的結果。您傳送給辨識器的 WriteArea 物件不一定要與螢幕上的實體寫入區域完全一致。以這種方式變更 WriteArea 高度,在部分語言上效果會更好。

指定寫入區域時,請在和筆劃座標相同的單位中指定寬度和高度。x、y 座標引數沒有單位要求,API 會將所有單位正規化,因此最重要的是筆劃的相對大小和位置。您可以自由輸入任何適合您的系統的座標,

前後脈絡

預先結構定義是您嘗試辨識的 Ink 中筆觸之前的文字。建議你告訴他們,該前一部將說明背景資訊。

例如,「n」和「u」之類的草字經常被誤認。如果使用者已輸入部分字詞「arg」,他們可能會繼續系統判定為「ument」或「nment」的筆劃。指定前內容「arg」可解決混淆,因為「argument」這個字詞比「argnment」更有可能。

預先背景資訊也有助於辨識者辨識字詞換行,以及字詞之間的空格。您可以輸入空格字元,但無法畫出字元,該如何辨識內容是否能夠判斷某個字詞何時結束?如果使用者已寫入「hello」並繼續寫入「world」,則不需預先背景資訊,辨識器會傳回「world」字串。不過,如果您指定預先內容,「hello」則會傳回模型「亦即」字串 (亦即開頭的空格),因為「hello world」比「helloword」更合理。

您應提供最長的預先內容字串,長度上限為 20 個字元,包括空格。如果字串較長,辨識器只會使用最後 20 個字元。

以下程式碼範例說明如何定義寫入區域,並使用 RecognitionContext 物件指定預先背景資訊。

Swift

let ink: Ink = ...;
let recognizer: DigitalInkRecognizer =  ...;
let preContext: String = ...;
let writingArea = WritingArea.init(width: ..., height: ...);

let context: DigitalInkRecognitionContext.init(
    preContext: preContext,
    writingArea: writingArea);

recognizer.recognizeHandwriting(
  from: ink,
  context: context,
  completion: {
    (result: DigitalInkRecognitionResult?, error: Error?) in
    if let result = result, let candidate = result.candidates.first {
      NSLog("Recognized \(candidate.text)")
    } else {
      NSLog("Recognition error \(error)")
    }
  })

Objective-C

MLKInk *ink = ...;
MLKDigitalInkRecognizer *recognizer = ...;
NSString *preContext = ...;
MLKWritingArea *writingArea = [MLKWritingArea initWithWidth:...
                                              height:...];

MLKDigitalInkRecognitionContext *context = [MLKDigitalInkRecognitionContext
       initWithPreContext:preContext
       writingArea:writingArea];

[recognizer recognizeHandwritingFromInk:ink
            context:context
            completion:^(MLKDigitalInkRecognitionResult
                         *_Nullable result, NSError *_Nullable error) {
                               NSLog(@"Recognition result %@",
                                     result.candidates[0].text);
                         }];

筆觸排序

辨識準確度對筆觸順序的影響很敏感。辨識器會預期中生的筆劃順序會自然而然,例如由左到右書寫的英文。任何從這個模式下出現的案件 (例如從最後一個字詞開始編寫英文句子) 都會產生較不準確的結果。

再舉一例,移除 Ink 中間的文字後,替換成其他字詞。修訂版本可能位於句子中間,但修訂版本的筆劃可能出現在筆劃序列結尾。在這種情況下,我們建議您將新撰寫的字詞分別傳送到 API,並透過自己的邏輯將結果與之前的辨識結果合併。

處理模稜兩可的形狀

在某些情況下,提供給辨識器的形狀含義並不明確。舉例來說,矩形的極圓角可以視為矩形或刪節號。

當有這類不明確的案例時,使用分數 (如有) 即可加以處理。只有形狀分類器會提供分數。如果模型非常有信心,結果的分數會遠高於第二名。如果不確定,前兩名結果的分數將會很接近。另請注意,形狀分類器會將整個 Ink 解譯為單一形狀。舉例來說,如果 Ink 包含彼此相鄰的矩形和刪節號,由於辨識器無法表示兩個形狀,因此辨識器可能會傳回其中一個 (或完全不同的) 作為結果。