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」を指定すると、「argnment」よりも「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 に個別に送信し、独自のロジックを使用して結果を以前の認識結果と統合することをおすすめします。
曖昧な形状に対処する
認識ツールに提供されたシェイプの意味が曖昧な場合があります。たとえば、角が丸い長方形は、長方形または楕円として認識される可能性があります。
このような不明確なケースは、認識スコアが利用可能な場合は認識スコアを使用して処理できます。スコアを提供するシェイプ分類子は 1 つだけです。モデルの信頼性が高い場合、最上位の結果のスコアは 2 番目の結果よりもはるかに高くなります。不確実性がある場合、上位 2 つの結果のスコアは近くなります。また、シェイプ分類子は Ink
全体を 1 つのシェイプとして解釈することにも注意してください。たとえば、Ink
に長方形と楕円が隣り合って含まれている場合、1 つの認識候補で 2 つの図形を表すことはできないため、認識ツールは結果としてどちらか一方(またはまったく異なるもの)を返す可能性があります。