ML Kit のデジタルインク認識機能を使用すると、数百もの言語で、デジタル表示面の手書き文字を認識できるだけでなく、スケッチを分類することもできます。
試してみる
- サンプルアプリで この API の使用例をご確認ください。
始める前に
Podfile に次の ML Kit ライブラリを含めます。
pod 'GoogleMLKit/DigitalInkRecognition', '8.0.0'プロジェクトの 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」の違いや、カンマとスラッシュの違いなどです。
書き込み領域の幅と高さを認識ツールに伝えることで、精度を向上させることができます。ただし、認識ツールは、書き込み領域に 1 行のテキストのみが含まれていることを前提としています。物理的な書き込み領域が十分に大きく、ユーザーが 2 行以上書き込める場合は、1 行のテキストの高さの最適な推定値である高さを持つ WritingArea を渡すことで、より良い結果が得られることがあります。認識ツールに渡す WritingArea オブジェクトは、画面上の物理的な書き込み領域と完全に一致する必要はありません。このように WritingArea の高さを変更すると、言語によっては効果が高くなります。
書き込み領域を指定する場合は、ストローク座標と同じ単位で幅と高さを指定します。x,y 座標引数には単位の要件はありません。API はすべての単位を正規化するため、重要なのはストロークの相対的なサイズと位置だけです。システムに適したスケールで座標を渡すことができます。
プリコンテキスト
プリコンテキストは、認識しようとしている Ink のストロークの直前のテキストです。プリコンテキストを認識ツールに伝えることで、認識ツールを支援できます。
たとえば、筆記体の文字「n」と「u」はよく間違われます。ユーザーがすでに「arg」という単語の一部を入力している場合、「ument」または「nment」として認識できるストロークを続ける可能性があります。プリコンテキスト「arg」を指定すると、「argument」という単語は「argnment」よりも可能性が高いため、曖昧さが解消されます。
プリコンテキストは、認識ツールが単語の区切り(単語間のスペース)を識別するのにも役立ちます。スペース文字を入力することはできますが、描画することはできません。認識ツールは、単語の終わりと次の単語の始まりをどのように判断するのでしょうか。 ユーザーがすでに「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 に個別に送信し、独自のロジックを使用して結果を以前の認識結果とマージすることをおすすめします。
曖昧な図形に対処する
認識ツールに提供される図形の意味が曖昧な場合があります。たとえば、角が丸い長方形は、長方形または楕円として認識される可能性があります。
このような不明確なケースは、認識スコアが利用可能な場合は、認識スコアを使用して処理できます。スコアを提供する図形分類子は 1 つだけです。モデルの信頼度が高い場合、上位の結果のスコアは 2 番目の結果よりもはるかに高くなります。不確実な場合は、上位 2 つの結果のスコアが近くなります。また、図形分類子は Ink 全体を 1 つの図形として解釈することに注意してください。たとえば、Ink に長方形と楕円が隣接している場合、1 つの認識候補で 2 つの図形を表すことはできないため、認識ツールはどちらか一方(またはまったく異なるもの)を結果として返すことがあります。