You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google ML-Kit处理AVFoundation图像时竖屏模式无识别结果

解决MLKit竖屏图像文字识别无结果的问题

核心原因

AVFoundation捕获的竖屏UIImage,其imageOrientation属性并非MLKit默认预期的.up方向(对应横屏Home键朝右的状态),导致MLKit按错误方向解析图像,无法识别文字;而横屏Home键朝右时,图像方向刚好匹配MLKit默认值,所以能正常识别。

修复方案

1. 给VisionImage设置正确的方向元数据

修改你的runTextRecognition(with:)方法,为VisionImage添加图像方向信息:

func runTextRecognition(with image: UIImage) {
    let visionImage = VisionImage(image: image)
    // 绑定UIImage的方向到VisionImage的元数据中
    let imageMetadata = ImageMetadata()
    imageMetadata.orientation = image.imageOrientation
    visionImage.metadata = imageMetadata
    
    textRecognizer.process(visionImage) { features, error in
        self.processResult(from: features, error: error)
    }
}

2. 验证CameraController中的图像方向传递

确保从AVFoundation获取的UIImage方向正确,可在捕获输出的代理方法中添加方向修正逻辑(可选但推荐):

// 示例:AVCapturePhotoCaptureDelegate的回调方法
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    guard let imageData = photo.fileDataRepresentation(),
          let originalImage = UIImage(data: imageData) else {
        return
    }
    // 修正图像方向为标准方向
    let fixedImage = originalImage.fixOrientation()
    runTextRecognition(with: fixedImage)
}

添加UIImage扩展实现方向修正:

extension UIImage {
    func fixOrientation() -> UIImage {
        guard imageOrientation != .up else { return self }
        
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(in: CGRect(origin: .zero, size: size))
        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return normalizedImage ?? self
    }
}

原理解释

MLKit的文字识别功能默认以.up方向(横屏Home键朝右)作为图像的基准方向。当竖屏拍摄时,UIImage的实际方向为.right或.left,但图像像素数据是旋转后的状态,MLKit如果未获取到方向元数据,会按基准方向解析,相当于识别了旋转90度的图像,因此无法检测到文字。通过设置VisionImage的metadata.orientation,让MLKit根据图像实际方向调整识别逻辑,即可解决竖屏识别失效的问题。

内容的提问来源于stack exchange,提问作者Lukas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:09:32