未检测到静态图像中的QR码

时间:2015-12-10 15:30:04

标签: ios

我想从静止图像中检测qrcode 这是代码

let ciimage =  <Load image from asset and covert to CIImage>
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context:nil, options:nil)
let features = detector.featuresInImage(ciimage)
print(features.count)

图像是正确的CIImage实例,它有QRCode但我总是没有功能,有没有人有同样的问题?

非常感谢。

1 个答案:

答案 0 :(得分:0)

我想我找到了答案

  • 该代码仅适用于 Playground 真正的iPhone 永远不会在模拟器上运行

  • 我使用 CIQRCodeGenerator CoreImage过滤器生成QRCode图像。

我希望有人可以在这里查看我的答案并给我建议。

以下是我使用的源代码

enum QRCodeUtilError:ErrorType{
    case GenerationFailed
}

extension UIImage {
    /**
     This function trys to return CIImage even the image is CGImageRef based.
     - Returns: CIImage equal to current image
    */
    func ciImage() -> CoreImage.CIImage?{
        // if CIImage is not nil then return it
        if self.CIImage != nil {
            return self.CIImage
        }

        guard let cgImage = self.CGImage else {
            return nil
        }
        return CoreImage.CIImage(CGImage: cgImage)
    }
}

/**
QRCode utility class
*/
class QRCodeUtil{
    /**
     Generates 'H' mode qrcode image
     - Parameter qrCode: QRCode String
     - Returns: Optional UIImage instance of QRCode
     */
    class func imageForQrCode(qrCode:String) throws -> UIImage{
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else {
            throw QRCodeUtilError.GenerationFailed
        }
        guard let data = qrCode.dataUsingEncoding(NSISOLatin1StringEncoding) else {
            throw QRCodeUtilError.GenerationFailed
        }
        filter.setValue(data, forKey: "inputMessage")
        filter.setValue("H", forKey: "inputCorrectionLevel")

        guard let outputImage = filter.outputImage else {
            throw QRCodeUtilError.GenerationFailed
        }

        /* 
    Convert the image to CGImage based because
    it crashes when saving image using
    UIImagePNGRepresentation or UIImageJPEGRepresentation
    if image is CIImage based. 
    */
        let context = CIContext(options: nil)
        let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent)
        return UIImage(CGImage: cgImage)
    }

    /**
     Detects QRCode from string
     - Parameter qrImage: UIImage which has QRCode
     - Returns: QRCode detected
    */
    class func qrCodeFromImage(qrImage:UIImage) -> String {
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
        guard let ciImage = qrImage.ciImage() else {
            return ""
        }
        guard let feature = detector.featuresInImage(ciImage).last as? CIQRCodeFeature else {
            return ""
        }
        return feature.messageString
    }
}