iOS上的MLKit文本检测适用于从Assets.xcassets拍摄的照片,但不适用于在相机上拍摄的同一照片/从相机胶卷上传的照片

时间:2018-11-05 22:38:45

标签: ios uiimage avfoundation text-recognition firebase-mlkit

我正在使用MLKit中的Google文本检测API来检测图像中的文本。它似乎可以完美地用于屏幕截图,但是当我尝试将其用于应用(使用AVFoundation)在应用中拍摄的图像或相机胶卷上传的照片时,会吐出少量看似随机的字符。

这是我用于运行实际文本检测的代码:

func runTextRecognition(with image: UIImage) {
    let visionImage = VisionImage(image: image)
    textRecognizer.process(visionImage) { features, error in
        self.processResult(from: features, error: error)
    }
}

func processResult(from text: VisionText?, error: Error?) {
    guard error == nil, let text = text else {
        print("oops")
        return
    }
    let detectedText = text.text

    let okAlert = UIAlertAction(title: "OK", style: .default) { (action) in
        // handle user input
    }

    let alert = UIAlertController(title: "Detected text", message: detectedText, preferredStyle: .alert)
    alert.addAction(okAlert)

    self.present(alert, animated: true) {
        print("alert was presented")
    }
}

这是我使用相机胶卷中的图像的代码(适用于屏幕截图,不适用于相机拍摄的图像):

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage {
        self.runTextRecognition(with: image)
        uploadView.image = image
    } else {
        print("error")
    }
    self.dismiss(animated: true, completion: nil)
}

这是我的代码,用于在应用程序内使用在相机上拍摄的照片(永远无效,结果总是胡说八道):

func photoOutput(_ output: AVCapturePhotoOutput,
                 didFinishProcessingPhoto photo: AVCapturePhoto,
                 error: Error?) {
    PHPhotoLibrary.shared().performChanges( {
        let creationRequest = PHAssetCreationRequest.forAsset()
        creationRequest.addResource(with: PHAssetResourceType.photo, data: photo.fileDataRepresentation()!, options: nil)
    }, completionHandler: nil)

    let testImage = UIImage(data: photo.fileDataRepresentation()!)

    self.runTextRecognition(with: testImage!)
}

这就是我使用放在Assets.xcassets中的测试图像所做的工作(这是唯一一贯工作良好的图像):

let uiimage = UIImage(named: "testImage")

self.runTextRecognition(with: uiimage!)

我认为我的问题可能在于UIImage的方向,但我不确定。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果图像选择器工作正常,则可能是图像方向问题。为了进行快速测试,您可以以不同的方向捕获多张图像,并查看其是否有效。

我的问题是文本识别是根据从画廊而非相机拍摄的图像进行的。那是定位问题。

解决方案1 ​​

在转换为视觉图像之前,请按以下步骤固定图像方向。

let fixedImage = pickedImage.fixImageOrientation()

添加此扩展名。

extension UIImage {
    func fixImageOrientation() -> UIImage {
        UIGraphicsBeginImageContext(self.size)
        self.draw(at: .zero)
        let fixedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return fixedImage ?? self
    } }

解决方案2

Firebase文档提供了一种针对所有方向进行修复的方法。

func imageOrientation(
    deviceOrientation: UIDeviceOrientation,
    cameraPosition: AVCaptureDevice.Position
    ) -> VisionDetectorImageOrientation {
    switch deviceOrientation {
    case .portrait:
        return cameraPosition == .front ? .leftTop : .rightTop
    case .landscapeLeft:
        return cameraPosition == .front ? .bottomLeft : .topLeft
    case .portraitUpsideDown:
        return cameraPosition == .front ? .rightBottom : .leftBottom
    case .landscapeRight:
        return cameraPosition == .front ? .topRight : .bottomRight
    case .faceDown, .faceUp, .unknown:
        return .leftTop
    }
}

创建元数据:

let cameraPosition = AVCaptureDevice.Position.back  // Set to the capture device you used.
let metadata = VisionImageMetadata()
metadata.orientation = imageOrientation(
    deviceOrientation: UIDevice.current.orientation,
    cameraPosition: cameraPosition
)

将元数据设置为视觉图像。

let image = VisionImage(buffer: sampleBuffer)
image.metadata = metadata