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

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

馬上試試

事前準備

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

    pod 'GoogleMLKit/DigitalInkRecognition', '3.2.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」,以及逗號和正斜線之間的差。

告知辨識器能改善書寫區域的寬度和高度。不過,辨識工具會假設寫入區域只包含一行文字。如果實體寫入區域的範圍夠大,可讓使用者寫入兩行或更多行,則只要傳入高度預估的單行文字高度的 WriteArea,可能會獲得更好的結果。您傳遞至辨識工具的 WriteArea 物件不必與畫面上的實體寫入區域完全相符。在部分語言中,以這種方式變更 WriteArea 高度的效果較佳。

指定書寫區域時,請使用與筆劃座標相同的單位指定寬度和高度。x,y 座標引數沒有單位要求;API 會將所有單位正規化,因此唯一重要的是,筆劃的相對大小和位置。您可以隨意傳入座標,設定適合您的系統規模。

預先背景資訊

前後脈絡是指您要識別的 Ink 中筆劃前方的文字。您可以提供預先背景資訊,協助辨識工具。

舉例來說,草寫字母「n」和「u」往往是錯的。如果使用者已輸入部分字詞「arg」,可能會以系統辨識為「ument」或「nment」的筆劃繼續。指定預先結構定義「arg」可解決模稜兩可的情況,因為「引數」這個字詞可能比「引數」的可能性較高。

預先背景資訊也可協助辨識器辨識分行符號 (字詞之間的空格)。您可以輸入空格字元,但無法繪製一個字元。那麼,辨識器要如何判斷當一個字詞何時結束和下一個字的開始?如果使用者已經寫入「hello」並繼續輸入「world」,在沒有預先背景資訊的情況下,辨識器會傳回「world」字串。但是,如果您指定預先上下文「hello」,模型會傳回「 world」字串並加上前置空格,這是因為「helloworld」比「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 包含一個矩形,而彼此相鄰的刪節號彼此相鄰,則辨識器可能會傳回另一個 (或完全不同的) 做為結果,因為單一辨識候選字詞無法代表兩個形狀。