最もシンプルな例
サンプルコード
- iOS: SimpleTextViewController.swift
- Android: SimpleTextScannerActivity.java
カメラを起動して画面に映った文字をログに出力する、最もシンプルな OCR の例です。
scan メソッドの呼び出し
カメラから取得した各フレームに対して scan メソッドを呼び出すことで、テキストの検出・認識を行います。
- iOS (Swift)
- Android (Java)
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
do {
let scanResult = try edgeOCR.scan(sampleBuffer, viewBounds: viewBounds)
for detection in scanResult.getTextDetections() {
let text = detection.getText()
if !text.isEmpty {
os_log("detected: %@", type: .debug, text)
}
}
} catch {
os_log("Failed to scan texts: %@", type: .debug, error.localizedDescription)
return
}
}
edgeOCR.scan には sampleBuffer に加えて、カメラ出力が表示されている画面のサイズ viewBounds を引数として渡します。
imageAnalysis.setAnalyzer(analysisExecutor, image -> {
if (!api.isReady()) {
image.close();
return;
}
try {
ScanResult scanResult = api.scan(image);
List<Text> detections = scanResult.getTextDetections();
for (Text detection : detections) {
String text = detection.getText();
if (!text.isEmpty()) {
Log.d("EdgeOCR", "detected: " + text);
}
}
} catch (EdgeError e) {
Log.e("EdgeOCR", "Failed to analyze image", e);
} finally {
image.close();
}
});
ScanResult について
scan メソッドの戻り値は ScanResult オブジェクトです。このオブジェクトから以下のメソッドで検出結果を取得できます。
| メソッド | 説明 |
|---|---|
getDetections() | すべての検出結果(Detection)を返す。Text または Barcode にキャスト可能 |
getTextDetections() | テキストの検出結果のみを返す |
getBarcodeDetections() | バーコードの検出結果のみを返す |
スキャン範囲内の対象物をすべてスキャンするため、複数の Detection オブジェクトが返されます。対象物は useModel で選択したモデルによってテキスト、バーコード、またはその両方です。