在 iOS 上使用 ML Kit 辨識數位墨水

有了 ML Kit 的數位墨水辨識功能,您便可識別數位平面上數百種語言的手寫文字,以及分類草圖。

立即試用

事前準備

  1. 在 Podfile 中加入下列 ML Kit 程式庫:

    pod 'GoogleMLKit/DigitalInkRecognition', '8.0.0'
    
    
  2. 安裝或更新專案的 Pod 後,請使用 .xcworkspace 開啟 Xcode 專案。Xcode 13.2.1 以上版本支援 ML Kit。

現在可以開始辨識 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.");
                                }];
}

提升文字辨識準確度的訣竅

文字辨識準確度可能因語言而異。準確度也取決於寫作風格。雖然數位墨水辨識功能經過訓練,可處理多種書寫風格,但結果可能因人而異。

以下提供幾種提升文字辨識器準確度的方法。請注意,這些技術不適用於表情符號、自動繪圖和形狀的繪圖分類器。

書寫區

許多應用程式都有明確定義的寫作區,供使用者輸入內容。符號的意義部分取決於符號相對於所含書寫區域的大小。例如,大小寫字母「o」或「c」的差異,以及逗號與正斜線的差異。

告知辨識器書寫區域的寬度和高度,有助於提高準確度。不過,辨識器會假設書寫區域只包含一行文字。如果實體書寫區夠大,可讓使用者書寫兩行以上的文字,您可以傳遞 WritingArea,並將高度設為單行文字高度的最佳估計值,這樣可能會獲得更準確的結果。傳遞至辨識器的 WritingArea 物件不必與螢幕上的實際書寫區域完全對應。以這種方式變更 WritingArea 高度,在某些語言中會比其他語言更有效。

指定書寫區域時,請以與筆劃座標相同的單位指定寬度和高度。x 和 y 座標引數沒有單位規定,因為 API 會將所有單位標準化,因此筆劃的相對大小和位置才是重點。您可以自由傳遞座標,並選擇適合系統的比例。

前文

前文是指您嘗試辨識的 Ink 中,筆劃前方的文字。你可以提供前文內容,協助辨識器辨識語音。

舉例來說,手寫體字母「n」和「u」經常會混淆。如果使用者已輸入部分字詞「arg」,他們可能會繼續輸入可辨識為「ument」或「nment」的筆劃。指定前文脈絡「arg」可解決模稜兩可的情況,因為「argument」比「argnment」更可能出現。

前文脈絡也能協助辨識器找出斷字位置,也就是字與字之間的空格。你可以輸入空格字元,但無法繪製空格字元,因此辨識器如何判斷一個字何時結束,下一個字何時開始?如果使用者已寫下「hello」,並繼續寫下「world」,在沒有前文的情況下,辨識器會傳回「world」字串。不過,如果您指定前文「hello」,模型會傳回「 world」字串 (開頭有空格),因為「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 包含一個矩形和一個相鄰的橢圓形,辨識器可能會傳回其中一個 (或完全不同的項目) 做為結果,因為單一辨識候選項目無法代表兩個形狀。