无法使用Firebase的MLKit从图像中检测条形码

时间:2018-08-09 10:47:16

标签: ios swift barcode firebase-mlkit

因此,我正在尝试使用MLKit扫描条形码,但是self.barcodeDetector?.detect的完成块中的条形码变量中没有条形码。

UIImage(名为:“ 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)
    }
}

所以问题在于条形码var为空,因此无法到达for循环中的代码...:

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

P.s。错误变量= nil,所以这不是问题。

使用的图像: enter image description here

2 个答案:

答案 0 :(得分:1)

您很可能会丢失图像的“方向”。

// 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)

答案 1 :(得分:1)

验证您已在pod文件中添加以下行:

pod 'Firebase / MLVisionBarcodeModel'