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

有了 ML Kit 的數位墨水辨識功能,您就能辨識數位表面上數百種語言的手寫文字,以及將素描分類。

立即體驗

事前準備

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

    pod 'GoogleMLKit/DigitalInkRecognition', '3.2.0'
    
    
  2. 安裝或更新專案的 Pod 後,請使用其 .xcworkspace 開啟 Xcode 專案。ML Kit 適用於 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.");
                                }];
}

提昇文字辨識準確度的提示

文字辨識的準確度可能因語言而異。準確率也取決於寫作風格雖然數位墨水辨識已經過訓練,可處理多種書寫樣式,但產生的結果可能因使用者而異。

歡迎參考下列幾種方法,提昇文字辨識工具的準確度。請注意,這些技巧不適用於表情符號、自動繪圖和形狀的繪圖分類器。

書寫區域

許多應用程式都有定義使用者輸入內容的寫入區域,部分符號的意義有一部分取決於其大小 (相對於包含符號的撰寫區域大小)。例如,小寫或大寫英文字母「o」或「c」,以及逗號與正斜線之間的差異。

告知辨識工具書寫區域的寬度和高度可提高準確度。然而,辨識器會假設寫入區域僅包含單行文字。如果實體寫入區域夠大,讓使用者可以撰寫兩行或更多行,則以最適合單行文字高度預估高度的 WriterArea 傳入,可能會獲得比較好的結果。您傳遞至辨識工具的 WriteArea 物件不需要與螢幕上的實體寫入區域完全相符。在部分語言中,以這種方式變更「寫入區域」高度的效果會更好。

指定書寫區域時,請在與筆劃座標相同的單位中指定寬度和高度。x,y 座標引數沒有任何單位要求 - API 會將所有單位正規化,因此唯一的重點是筆劃的相對大小和位置。您可以依照系統適合的比例,將座標傳入座標。

事前情境

「前置情境」是指在您嘗試辨識的 Ink 中,緊接在筆劃之前的文字。您可以將預先上下文告知辨識工具,協助辨識工具。

例如,草寫字母「n」和「u」通常被誤認為另一個字。如果使用者已輸入部分字詞「arg」,則可能會繼續做出能辨識為「ument」或「nment」的筆劃。指定預先結構定義「arg」可解決模稜兩可的情況,因為「引數」這個字詞可能比「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 含有一個矩形和相鄰的橢圓形,辨識器可能會傳回其中一個 (或完全不同的) 做為結果,因為單一辨識候選項目不能代表兩個形狀。