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 に描画するサンプル関数が含まれています。これは、アプリケーションに合わせて調整する必要があります。線分を描画するときは丸キャップを使用して、長さがゼロの線分がドットとして描画されるようにすることをおすすめします(小文字の「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.");
                                }];
}

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

テキスト認識の精度は言語によって異なります。精度は文章のスタイルにも左右されます。デジタルインク認識はさまざまな種類の書体を処理するようにトレーニングされていますが、結果はユーザーによって異なります。

テキスト認識機能の精度を向上させる方法は次のとおりです。なお、これらの手法は、絵文字、自動描画、シェイプの描画分類には適用されません。

書き込み領域

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

認識機能に書き込み領域の幅と高さを認識させると、精度が向上します。ただし、認識機能では、書き込み領域にはテキストが 1 行しか含まれていないと想定されます。物理的な書き込み領域が 2 行以上書き込めるほど大きい場合は、1 行の高さを最も適切に推定できる高さで WritingArea を渡すことでより良い結果が得られることがあります。認識ツールに渡す WritingArea オブジェクトは、画面上の物理的な書き込み領域と正確に一致する必要はありません。この方法で WritingArea の高さを変更すると、一部の言語ではうまく機能しません。

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

事前コンテキスト

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

たとえば、手書き文字「n」と「u」はよく間違えられます。ユーザーが部分的な単語「arg」をすでに入力している場合は、「ument」または「nment」として認識できるストロークが続くことがあります。事前コンテキストの「arg」を指定すると、「argument」という単語の方が「argnment」よりも可能性が高いため、あいまいさが解消されます。

事前コンテキストは、認識機能が単語の区切り(単語間のスペース)を識別するのにも役立ちます。空白文字は入力できますが、描画はできません。認識機能では、ある単語が終了して次の単語が開始するタイミングをどのように判断できるでしょうか。ユーザーがすでに「hello」と記述していて、「world」という単語が続く場合、事前コンテキストなしで認識ツールは文字列「world」を返します。ただし、事前コンテキストの「hello」を指定すると、「hello world」のほうが「helloword」よりも意味があるので、モデルは先頭にスペースが付いた文字列「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);
                         }];

ストロークの順序

認識の精度は、ストロークの順序に左右されます。認識ツールは、人が自然に書く順序でストロークが発生することを想定しています。たとえば、英語の場合は左から右に記述します。最後の単語から英語の文を書くなど、このパターンから逸脱するケースでは、結果の精度が低下します。

もう 1 つの例は、Ink の途中の単語が削除され、別の単語に置き換えられる場合です。リビジョンは文の途中にありますが、リビジョンのストロークはストローク シーケンスの末尾にあります。この場合は、新しく書き込まれた単語を個別に API に送信し、独自のロジックを使用してその結果を以前の認識結果と統合することをおすすめします。

あいまいな図形への対処

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

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