ML Kit を使用してデジタルインクを認識する(iOS)

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 に描画するサンプル関数が含まれています。この関数は、アプリケーションに合わせて調整する必要があります。線分を描画する際はラウンドキャップを使用して、長さが 0 の線分がドットとして描画されるようにすることをおすすめします(小文字の 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 オブジェクトを認識する

次に、わかりやすくするために touchesEnded() から呼び出される doRecognition() 関数を見ていきましょう。他のアプリケーションでは、タイムアウト後、またはユーザーが認識をトリガーするためにボタンを押した場合にのみ、認識を呼び出す必要がある場合があります。

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.");
                                }];
}

テキスト認識の精度を向上させるためのヒント

テキスト認識の精度は言語によって異なります。正確性は文章のスタイルにも 依存しますデジタルインク認識はさまざまな種類の筆記スタイルを処理するようにトレーニングされていますが、結果はユーザーによって異なる場合があります。

テキスト認識の精度を向上させる方法をいくつか紹介します。これらの手法は、絵文字、AutoDraw、シェイプの描画分類には適用されない点に注意してください。

書き込みエリア

多くのアプリケーションには、ユーザー入力用の書き込み領域が明確に定義されています。シンボルの意味は、シンボルを含む書き込み領域のサイズに対する相対的なサイズによって部分的に決定されます。たとえば、小文字または大文字の「o」や「c」の違い、カンマとスラッシュの違いなどです。

入力領域の幅と高さを認識機能に伝えると、精度が向上します。ただし、認識ツールは、書き込み領域に 1 行のテキストしか含まれていないと想定します。物理的な書き込み領域が十分な大きさで、ユーザーが 2 行以上書き込める場合は、テキストの 1 行の高さを最適に見積もった高さで WritingArea を渡すことで、より適切な結果が得られることがあります。認識ツールに渡す WritingArea オブジェクトは、画面上の物理的な書き込み領域と完全に一致させる必要はありません。この方法で WritingArea の高さを変更すると、言語によって効果が上がります。

書き込み領域を指定する際は、その幅と高さをストローク座標と同じ単位で指定します。x 座標と y 座標の引数に単位を指定する必要はありません。API はすべての単位を正規化するため、重要なのは、ストロークの相対的なサイズと位置だけです。座標はシステムに合わせて任意のスケールで渡すことができます。

事前コンテキスト

プリコンテキストとは、認識しようとしている Ink のストロークの直前にあるテキストのことです。事前コンテキストを伝えると、認識機能に役立ちます。

たとえば、筆記体「n」と「u」はしばしば間違えられます。「arg」の部分的な単語をすでに入力している場合は、「ument」または「nment」として認識できるストロークが続行されることがあります。プリコンテキストの「arg」を指定すると、「argument」という単語よりも「argument」という単語が使用される可能性が高いため、曖昧さが解決されます。

事前コンテキストは、認識機能で単語の区切り(単語間のスペース)を特定するのにも役立ちます。スペースは入力できますが、描画できないため、認識機能によって、ある単語の終了と次の単語の開始のタイミングはどのように判断できるでしょうか。ユーザーがすでに「hello」と書かれ、「world」と書かれた単語が続く場合、事前コンテキストなしで認識ツールは文字列「world」を返します。ただし、プリコンテキストの「hello」を指定すると、「helloword」よりも「hello world」という方が理にかなっているため、モデルは先頭にスペースを付加して「world」という文字列を返します。

プリコンテキスト文字列をできるだけ長く指定してください(スペースを含めて 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 に送信し、独自のロジックを使用して、その結果を以前の認識と統合することをおすすめします。

あいまいな形状に対処する

認識ツールに提供されるシェイプの意味があいまいな場合があります。たとえば、角が非常に丸い長方形は、長方形または楕円として表示されます。

このような不明確なケースは、認識スコアを使用して処理できます(利用可能な場合)。シェイプ分類器のみがスコアを提供します。モデルの信頼度が非常に高い場合、上位の結果のスコアは 2 番目に良い結果よりもはるかに優れています。不確実性がある場合は、上位 2 つの結果のスコアが近くなります。また、シェイプ分類器は Ink 全体を 1 つのシェイプとして解釈することにも留意してください。たとえば、Ink に長方形と楕円が隣接している場合、認識機能は結果としてどちらか一方(またはまったく異なるもの)を返す可能性があります。これは、1 つの認識候補が 2 つの形状を表現できないためです。