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

バーコードスキャン

scan メソッドを使用して、画像内のバーコードをスキャンできます。

モデルの選択

バーコード専用モデル edgeocr_barcode_defaultuseModel で指定します。

OCR とバーコード認識を同時に使用する場合

テキスト認識とバーコード認識を同時に行いたい場合は、model-d{width}x{height}_with_barcode(例: model-d320x320_with_barcode)を指定してください。

読み取り回数の設定

バーコードフォーマットごとに確定までの読み取り回数を設定できます。

// QR コードのみ 5 回読み取り後に確定
let barcodeFormats = [BarcodeFormat.QRCode: 5]
let modelSettings = ModelSettings(barcodeNToConfirm: barcodeFormats)
loadModelAndNavigate(
destination: .barcodeView,
uid: "edgeocr_barcode_default",
modelSettings: modelSettings)

バーコードスキャンの実装

scanBarcodes メソッドでバーコードをスキャンし、ScanConfirmationStatus.Confirmed のバーコードのみを結果として使用します。

func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
let scanResult: ScanResult
do {
scanResult = try edgeOCR.scanBracodes(
sampleBuffer,
barcodeScanOption: barcodeScanOption,
viewBounds: viewBounds)
} catch {
os_log("Failed to scan: %@", type: .debug, error.localizedDescription)
return
}

DispatchQueue.main.async { [weak self] in
self?.drawDetections(result: scanResult)
}
}

func drawDetections(result: ScanResult) {
var detections: [Barcode] = []
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
detectionLayer.sublayers = nil
for detection in result.getBarcodeDetections() {
if detection.getStatus() == ScanConfirmationStatus.Confirmed {
let bbox = detection.getBoundingBox()
drawDetection(bbox: bbox, text: detection.getText())
detections.append(detection)
}
}
CATransaction.commit()

if detections.count > 0 && !showDialog {
showDialog(detections: detections)
}
}

スキャン状態のリセット

結果表示後に resetScanningState() を呼び出すことで、読み取り回数のカウントをリセットできます。

edgeOCR.resetScanningState()
注記

バーコードスキャナのデフォルトの検出範囲は入力画像の全体です。そのため、ModelInformation から得られるアスペクト比は 0 に設定されています。