LoginSignup
2

More than 1 year has passed since last update.

Visionのバーコード検出は、複数の種類のバーコードを一度に読み取ることができる。
医療分野などの業務用に活躍も考えられる。

Dec-10-2021 08-08-16.gif

検出方法

let detectBarcodeRequest = VNDetectBarcodesRequest()
detectBarcodeRequest.revision = VNDetectBarcodesRequestRevision2
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right, options: [:])
do {
    try handler.perform([detectBarcodeRequest])
    guard let observations = detectBarcodeRequest.results as? [VNBarcodeObservation] else { return }
} catch {
    print("Vision error: \(error.localizedDescription)")
}

結果には以下が含まれる。
バーコードのバウンディングボックス(0~1の値に正規化された座標)
ペイロードから読み取った文字列
バーコードの種類
低レベルのデスクリプション(CIImageでバーコードを再生成するときに使う)

QRコードのような2次元バーコードは全体を囲むボックス、1次元のバーコードは横に直線で読み取った細いボックスが返される。

for observation in detectBarcodeRequest {
    print(observation.boundingBox)
    print(observation.payloadStringValue)
    print(observation.symbology)
    print(observation.barcodeDescriptor)
}

(0.01536397757353606, 0.5692257563273112, 0.38412154692190664, 0.21521108945210776)
Optional("https://ja.wikipedia.org/")
VNBarcodeSymbology(_rawValue: VNBarcodeSymbologyQR)
Optional(CIQRCodeDescriptor: 0x28112bd50)

(0.5915124398690683, 0.5233462015787761, 0.15230130796079278, 0.08319133122762035)
Optional("http://www.irasutoya.com/")
VNBarcodeSymbology(_rawValue: VNBarcodeSymbologyQR)
Optional(CIQRCodeDescriptor: 0x28112a1f0)

(0.27184558444552953, 0.37421875, 0.27779362996419266, 0.0015625000000000222)
Optional("Wikipedia")
VNBarcodeSymbology(_rawValue: VNBarcodeSymbologyCode128)
nil

デフォルトでは認識できる全てのバーコードが観測される。
認識するバーコードの種類を指定する。

detectBarcodeRequest.symbologies = [.qr] //配列なので複数指定もできる。

認識できるバーコードの種類は以下。

.aztec
.codabar
.code128.
.code39
.code39Checksum
.code39FullASCII
.code39FullASCIIChecksum
.code93
.code93i
.dataMatrix
.ean13
.ean8
.gs1DataBar
.gs1DataBarExpanded
.gs1DataBarLimited
.i2of5
.i2of5Checksum
.itf14
.microPDF417
.microQR
.pdf417
.qr
.upce

フレーム内の特定の領域に注目して結果を取得することもできる。
この場合、注目領域内の座標が返される。

detectBarcodeRequest.regionOfInterest = CGRect(x: 0.1, y: 0.1, width: 0.4, height: 0.4)

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
簡単な開発内容をお書き添えの上、お気軽にご連絡ください。
rockyshikoku@gmail.com

Core MLやARKitを使ったアプリを作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2