7

所以,我正在尝试使用 MLKit 扫描条形码,但self.barcodeDetector?.detect.

UIImage(named: "barcode.jpg") 存在并且被正确加载(并且有条形码)。

那么我做错了什么/我错过了什么?

private var barcodeDetector: VisionBarcodeDetector?
private lazy var vision = Vision.vision()

override func viewDidLoad() {
    super.viewDidLoad()

    guard let barcodeImage = self.imageView.image else { return }

    let format = VisionBarcodeFormat.all
    let barcodeOptions = VisionBarcodeDetectorOptions(formats: format)
    let barcodeDetector = self.vision.barcodeDetector(options: barcodeOptions)

    let imageMetadata = VisionImageMetadata()
    imageMetadata.orientation = UIUtilities.visionImageOrientation(from: barcodeImage.imageOrientation)

    let visionImage = VisionImage(image: barcodeImage)
    visionImage.metadata = imageMetadata

    self.textView.text = ""

    barcodeDetector.detect(in: visionImage) { (barcodes, error) in
    guard error == nil, let barcodes = barcodes, !barcodes.isEmpty else {
        let errorString = error?.localizedDescription ?? "No error description available"
        self.textView.text = "On-Device barcode detection failed with error: \(errorString)"
        return
    }

    self.textView.text = self.textView.text + "\(self.dateFormatter.string(from: Date())) detecting ...\n"
    self.textView.text = self.textView.text + "barcodes.count = \(barcodes.count)" + "\n"
    print(barcodes.count)

    for barcode in barcodes {
        self.textView.text = self.textView.text + "\(barcode)" + "\n"
        print(barcode)
    }
}

所以问题是barcodes var是空的,所以for循环中的代码没有到达......:

        for barcode in barcodes! {
            print(barcode.rawValue!)
        }

Ps 错误变量 = nil,所以这不是问题。

使用的图像: 在此处输入图像描述

4

2 回答 2

2

您很可能错过了图像的“方向”。

// Define the metadata for the image.
let imageMetadata = VisionImageMetadata()
imageMetadata.orientation = UIUtilities.visionImageOrientation(from: image.imageOrientation)

// Initialize a VisionImage object with the given UIImage.
let visionImage = VisionImage(image: image)
visionImage.metadata = imageMetadata

如果这不能解决,请尝试将条形码格式设置为“全部”

let format = VisionBarcodeFormat.all
let barcodeOptions = VisionBarcodeDetectorOptions(formats: format)
// Create a barcode detector.
let barcodeDetector = vision.barcodeDetector(options: barcodeOptions)
于 2018-08-10T19:31:04.337 回答
1

验证您是否已在 pod 文件中添加此行:

pod 'Firebase / MLVisionBarcodeModel'
于 2018-10-03T14:22:52.800 回答