メインコンテンツまでスキップ

最もシンプルな例

カメラを起動して画面に映った文字をログに出力する、最もシンプルな OCR の例です。

scan メソッドの呼び出し

カメラから取得した各フレームに対して scan メソッドを呼び出すことで、テキストの検出・認識を行います。

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 を引数として渡します。

ScanResult について

scan メソッドの戻り値は ScanResult オブジェクトです。このオブジェクトから以下のメソッドで検出結果を取得できます。

メソッド説明
getDetections()すべての検出結果(Detection)を返す。Text または Barcode にキャスト可能
getTextDetections()テキストの検出結果のみを返す
getBarcodeDetections()バーコードの検出結果のみを返す

スキャン範囲内の対象物をすべてスキャンするため、複数の Detection オブジェクトが返されます。対象物は useModel で選択したモデルによってテキスト、バーコード、またはその両方です。