有了 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."); }]; }
提升文字辨識準確度的訣竅
文字辨識的準確度可能因語言而異。準確度也取決於寫作風格。雖然數位筆跡辨識功能經過訓練,可處理多種書寫風格,但結果可能因使用者而異。
以下提供幾種方法,可提升文字辨識器的準確度。請注意,這些技術不適用於表情符號、Autodraw 和形狀的繪圖分類器。
寫作區
許多應用程式都有明確定義的書寫區域,供使用者輸入內容。符號的意義部分取決於其大小與所在書寫區域大小的相對關係。例如,大小寫字母「o」或「c」之間的差異,以及逗號與正斜線之間的差異。
告知辨識器書寫區域的寬度和高度,可提高準確度。不過,辨識器會假設書寫區域只包含一行文字。如果實體書寫區域夠大,可讓使用者書寫兩行以上,建議傳入 WritingArea,並將高度設為單行文字高度的最佳估計值,這樣可能會有更好的結果。您傳遞給辨識器的 WritingArea 物件不一定要與螢幕上的實體書寫區域完全對應。以這種方式變更 WritingArea 高度,在某些語言的效果會比其他語言更好。
指定書寫區域時,請以與筆劃座標相同的單位指定寬度和高度。x、y 座標引數沒有單位要求,API 會將所有單位正規化,因此唯一重要的是筆劃的相對大小和位置。您可以根據系統需求,自由傳入任何比例的座標。
前置背景資訊
前置內容是指您嘗試辨識的 Ink 中,筆劃之前的文字。您可以提供前置內容,協助辨識器辨識。
舉例來說,草寫字母「n」和「u」經常會混淆。如果使用者已輸入部分字詞「arg」,則可以繼續輸入可辨識為「ument」或「nment」的筆劃。指定前置語境「arg」可解決語意模糊的問題,因為「argument」一詞比「argnment」更可能出現。
前置內容也能協助辨識器找出字詞之間的空格。您可以輸入空格字元,但無法繪製空格字元,因此辨識器如何判斷一個字詞何時結束,下一個字詞何時開始?如果使用者已寫下「hello」,並繼續寫下「world」,在沒有預先內容的情況下,辨識器會傳回「world」字串。不過,如果指定前置內容「hello」,模型會傳回字串「 world」(開頭有空格),因為「hello world」比「helloword」更合理。
請盡可能提供最長的前置內容字串,最多 20 個字元 (含空格)。如果字串長度超過 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,並使用自己的邏輯將結果與先前的辨識結果合併。
處理模糊形狀
有時提供給辨識器的形狀意義不明確。例如,邊緣非常圓滑的矩形可能會被視為矩形或橢圓形。
這類不明確的情況可透過辨識分數處理 (如有)。只有形狀分類器會提供分數。如果模型非常有把握,則最佳結果的分數會遠高於次佳結果。如果無法確定,前兩項結果的分數會很接近。此外,請注意,形狀分類器會將整個 Ink 解讀為單一形狀。舉例來說,如果 Ink 包含相鄰的矩形和橢圓形,辨識器可能會傳回其中一個 (或完全不同的內容) 做為結果,因為單一辨識候選項目無法代表兩個形狀。