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

ML Kit のデジタルインク認識機能を使用すると、テキスト デジタル サーフェスを何百もの言語で扱ったり、スケッチを分類したりできます。

試してみる

始める前に

  1. Podfile に次の ML Kit ライブラリを含めます。

    pod 'GoogleMLKit/DigitalInkRecognition', '3.2.0'
    
    
  2. プロジェクトの Pod をインストールまたは更新したら、Xcode プロジェクトを開きます。 .xcworkspace を使用します。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 これらをアプリケーションに合わせて調整してください。Google Cloud コンソールの 線セグメントを描画する際にラウンドキャップにより、長さが 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 オブジェクトを認識する

次に、doRecognition() 関数について説明します。これは、わかりやすくするために、 touchesEnded() から。他のアプリケーションでは、3 つの nginx Pod を タイムアウトが発生したり、ユーザーがボタンを押してトリガーした後に限り、認識されます。 あります。

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 行以上書き込むのに十分な大きさである場合、 代わりに WritingArea を、 作成します。認識ツールに渡す WritingArea オブジェクトは、各オブジェクトの 画面上の手書き入力領域と完全に一致するようにします。この方法で WritingArea の高さを変更する 一部の言語では他よりも優れています。

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

事前コンテキスト

事前コンテキストとは、対象の Ink のストロークの直前に表示されるテキストです。 認識しようと試みます。事前コンテキストを伝えると、認識機能に役立ちます。

たとえば、手書きメモの「n」は、と「u」混同されがちですユーザーが 単語「arg」の部分がすでに入力されている場合、次のように認識できるストロークが続くことがあります。 "ument"または「nment」を使用します。プリコンテキスト「arg」の指定そのあいまいさが解決されます。というのも、単語が "引数"「argnment」よりも可能性が高いです。

事前コンテキストは、認識機能で単語の区切り(単語間のスペース)を特定するのにも役立ちます。Google Chat では スペースは入力しても描画できないため、認識ツールで 1 つの単語がいつ終わるかを判断するには、どうすればよいでしょうか。 次の問題は始まりますか?ユーザーがすでに「hello」と記述している場合続けて、次のように記述された単語を 「world」の場合、事前コンテキストがない場合、認識ツールは文字列「world」を返します。ただし、 事前コンテキスト「hello」の場合、モデルは文字列「「hello world」という単語を 「helloword」よりも意味があります。

プリコンテキスト文字列はできるだけ長く、半角 20 文字(全角 10 文字)以内で指定してください。 できます。文字列が長い場合、認識機能は最後の 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);
                         }];

ストロークの順序

認識の精度はストロークの順序に左右されます。認識ツールはストロークが 人が自然に書くような順序で行われます。たとえば英語の場合は「left-toright」と指定します。すべての場合 たとえば、最後の単語で始まる英語の文を書くなど、 結果の精度が低下します

別の例としては、Ink の途中の単語が削除され、 できます。改訂版はおそらく文の途中にあるが、改訂版のストローク ストローク シーケンスの最後に来ます。 この場合は、新しく記述された単語を個別に API に送信し、 独自のロジックで事前認識と変換できます。

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

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

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