So, i'am trying to scan a barcode with MLKit, but there are no barcodes in the barcode variable in the completion block of self.barcodeDetector?.detect
.
The UIImage(named: "barcode.jpg") exists and is loaded correctly (and has barcodes).
So what am I doing wrong/what am I missing?
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)
}
}
So the problem is that the barcodes var is empty so the code in the for loop is not reached...:
for barcode in barcodes! {
print(barcode.rawValue!)
}
P.s. The error variable = nil, so that's not the problem.
image used:
You are most likely missing the "orientation" of the image.
// 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
if that doesn't resolve, try setting the barcode format to "all"
let format = VisionBarcodeFormat.all
let barcodeOptions = VisionBarcodeDetectorOptions(formats: format)
// Create a barcode detector.
let barcodeDetector = vision.barcodeDetector(options: barcodeOptions)
Verify that you have added this line in your pod file:
pod 'Firebase / MLVisionBarcodeModel'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With