Reputation: 1676
I am trying to detect bar code from user selected image. I am able to detect QR code from the image but can not find anything related to bar code scanning from Image. The code I am using to detect QR code from image is like below:
func detectQRCode(_ image: UIImage?) -> [CIFeature]? {
if let image = image, let ciImage = CIImage.init(image: image){
var options: [String: Any]
let context = CIContext()
options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options)
if ciImage.properties.keys.contains((kCGImagePropertyOrientation as String)){
options = [CIDetectorImageOrientation: ciImage.properties[(kCGImagePropertyOrientation as String)] ?? 1]
}else {
options = [CIDetectorImageOrientation: 1]
}
let features = qrDetector?.features(in: ciImage, options: options)
return features
}
return nil
}
When I go into the documentation of the CIDetectorTypeQRCode
it says
/* Specifies a detector type for barcode detection. */
@available(iOS 8.0, *)
public let CIDetectorTypeQRCode: String
Though this is QR code Type documentation says it can detect barcode also.
Fine. But when I use the same function to decode barcode it returns me empty array of features. Even if it returns me some features how will I be able to convert it to the bar code alternative of CIQRCodeFeature
? I do not see any bar code alternative in the documentation of CIQRCodeFeature
. I know with ZBar SDK you can do this, but I am trying not to use any third party library here, or is it mandatory to use this in this regard??.
Please help, Thanks a lot.
Upvotes: 4
Views: 5497
Reputation: 678
You can use Vision Framework
Barcode detection request code
var vnBarCodeDetectionRequest : VNDetectBarcodesRequest{
let request = VNDetectBarcodesRequest { (request,error) in
if let error = error as NSError? {
print("Error in detecting - \(error)")
return
}
else {
guard let observations = request.results as? [VNDetectedObjectObservation]
else {
return
}
print("Observations are \(observations)")
}
}
return request
}
Function in which you need to pass the image.
func createVisionRequest(image: UIImage)
{
guard let cgImage = image.cgImage else {
return
}
let requestHandler = VNImageRequestHandler(cgImage: cgImage, orientation: image.cgImageOrientation, options: [:])
let vnRequests = [vnBarCodeDetectionRequest]
DispatchQueue.global(qos: .background).async {
do{
try requestHandler.perform(vnRequests)
}catch let error as NSError {
print("Error in performing Image request: \(error)")
}
}
}
Upvotes: 9