バーコードスキャン
サンプルコード
scan メソッドを使用して、画像内のバーコードをスキャンできます。
モデルの選択
バーコード専用モデル edgeocr_barcode_default を useModel で指定します。
OCR とバーコード認識を同時に使用する場合
テキスト認識とバーコード認識を同時に行いたい場合は、model-d{width}x{height}_with_barcode(例: model-d320x320_with_barcode)を指定してください。
読み取り回数の設定
バーコードフォーマットごとに確定までの読み取り回数を設定できます。
- iOS (Swift)
- Android (Java)
// QR コードのみ 5 回読み取り後に確定
let barcodeFormats = [BarcodeFormat.QRCode: 5]
let modelSettings = ModelSettings(barcodeNToConfirm: barcodeFormats)
loadModelAndNavigate(
destination: .barcodeView,
uid: "edgeocr_barcode_default",
modelSettings: modelSettings)
// QR コードのみ 5 回読み取り後に確定
ModelSettings modelSettings = new ModelSettings();
modelSettings.setBarcodeNToConfirm(
Collections.singletonMap(BarcodeFormat.QRCode, 5));
loadModelAndStartActivity(intent, "edgeocr_barcode_default", modelSettings);
バーコードスキャンの実装
- iOS (Swift)
- Android (Java)
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)
}
}
scan メソッドでスキャンし、ScanConfirmationStatus.Confirmed のバーコードのみを結果として使用します。
@Override
public void analyze(@NonNull ImageProxy image) {
try {
if (!isActive) return;
if (callback == null) return;
List<Barcode> targetDetections = new ArrayList<>();
ScanResult scanResult = api.scan(image);
for (Barcode detection : scanResult.getBarcodeDetections()) {
if (detection.getStatus() == ScanConfirmationStatus.Confirmed) {
targetDetections.add(detection);
}
}
callback.call(targetDetections);
} catch (EdgeError e) {
Log.e("EdgeOCR", Log.getStackTraceString(e));
} finally {
image.close();
}
}
スキャン状態のリセット
結果表示後に resetScanningState() を呼び出すことで、読み取り回数のカウントをリセットできます。
- iOS (Swift)
- Android (Java)
edgeOCR.resetScanningState()
api.resetScanningState();
注記
バーコードスキャナのデフォルトの検出範囲は入力画像の全体です。そのため、ModelInformation から得られるアスペクト比は 0 に設定されています。