在 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」,以及半形逗號和正斜線的差異。

告訴辨識器寫入區域的寬度和高度有助於提高準確度。不過,辨識器會假設寫入區域只包含一行文字。如果實體寫入區域夠大,且允許使用者編寫兩行或更多行,您可以傳入 ComposeArea,其高度代表單行文字的高度,進而獲得更好的結果。傳遞至辨識器的 WriteArea 物件不必與螢幕上的實體寫入區域完全一致。以這種方式變更 WriteArea 高度,在部分語言上發揮更好的效果。

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

預先背景資訊

預先結構定義是指在您要辨識的 Ink 中筆觸之前的文字。建議你告訴他們,預先背景資訊是相關資訊。

例如:草寫的字母「&」和「u」通常會互相誤導。如果使用者已輸入部分字詞「arg」,系統可能會繼續執行筆中稱為「ument」或「nment」的筆劃。指定預先背景資訊「arg」即可解決模稜兩可的問題,因為「argument」引數比較有可能「aargtment」。

預先背景資訊也有助於語音辨識器辨識字詞換行,以及字詞之間的空格。您可以輸入空格字元,但無法繪製一個字元,所以該如何辨識內容要如何判定其中一個字詞何時結束?如果使用者已寫入「hello.quot」,並繼續寫入「world」這個世界文字,但沒有前置背景資訊,則辨識器會傳回「quoWorld;」字串。不過,如果您指定預先結構定義「hello」,模型就會傳回「quot; world」字串,開頭的空格為「quot;hello world」,比「quot;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 包含彼此相鄰的矩形和刪節號,由於辨識單一的表示法無法代表兩個形狀,因此辨識器可能會傳回其中一個 (或完全不同的) 作為結果。