在 iOS 上使用 ML Kit 辨識圖片中的文字

您可以使用 ML Kit 辨識圖片或影片中的文字,例如路標上的文字。這項功能的主要特性如下:

Text Recognition v2 API
說明可辨識圖片或影片中的文字,並支援拉丁文、中文、德瓦納迦文、日文和韓文等多種語言
SDK 名稱GoogleMLKit/TextRecognition
GoogleMLKit/TextRecognitionChinese
GoogleMLKit/TextRecognitionDevanagari
GoogleMLKit/TextRecognitionJapanese
GoogleMLKit/TextRecognitionKorean
導入作業素材資源會在建構期間靜態連結至應用程式
應用程式大小影響每個指令碼 SDK 約 38 MB
成效在大多數裝置上,拉丁字母 SDK 可提供即時結果,其他裝置則較慢。

立即試用

事前準備

  1. 在 Podfile 中加入下列 ML Kit Pod:
    # To recognize Latin script
    pod 'GoogleMLKit/TextRecognition', '15.5.0'
    # To recognize Chinese script
    pod 'GoogleMLKit/TextRecognitionChinese', '15.5.0'
    # To recognize Devanagari script
    pod 'GoogleMLKit/TextRecognitionDevanagari', '15.5.0'
    # To recognize Japanese script
    pod 'GoogleMLKit/TextRecognitionJapanese', '15.5.0'
    # To recognize Korean script
    pod 'GoogleMLKit/TextRecognitionKorean', '15.5.0'
    
  2. 安裝或更新專案的 Pod 後,請使用 .xcworkspace 開啟 Xcode 專案。Xcode 12.4 以上版本支援 ML Kit。

1. 建立「TextRecognizer」的執行個體

請呼叫 +textRecognizer(options:),建立 TextRecognizer 的例項,並傳遞與您在上述宣告為依附元件的 SDK 相關的選項:

Swift

// When using Latin script recognition SDK
let latinOptions = TextRecognizerOptions()
let latinTextRecognizer = TextRecognizer.textRecognizer(options:options)

// When using Chinese script recognition SDK
let chineseOptions = ChineseTextRecognizerOptions()
let chineseTextRecognizer = TextRecognizer.textRecognizer(options:options)

// When using Devanagari script recognition SDK
let devanagariOptions = DevanagariTextRecognizerOptions()
let devanagariTextRecognizer = TextRecognizer.textRecognizer(options:options)

// When using Japanese script recognition SDK
let japaneseOptions = JapaneseTextRecognizerOptions()
let japaneseTextRecognizer = TextRecognizer.textRecognizer(options:options)

// When using Korean script recognition SDK
let koreanOptions = KoreanTextRecognizerOptions()
let koreanTextRecognizer = TextRecognizer.textRecognizer(options:options)

Objective-C

// When using Latin script recognition SDK
MLKTextRecognizerOptions *latinOptions = [[MLKTextRecognizerOptions alloc] init];
MLKTextRecognizer *latinTextRecognizer = [MLKTextRecognizer textRecognizerWithOptions:options];

// When using Chinese script recognition SDK
MLKChineseTextRecognizerOptions *chineseOptions = [[MLKChineseTextRecognizerOptions alloc] init];
MLKTextRecognizer *chineseTextRecognizer = [MLKTextRecognizer textRecognizerWithOptions:options];

// When using Devanagari script recognition SDK
MLKDevanagariTextRecognizerOptions *devanagariOptions = [[MLKDevanagariTextRecognizerOptions alloc] init];
MLKTextRecognizer *devanagariTextRecognizer = [MLKTextRecognizer textRecognizerWithOptions:options];

// When using Japanese script recognition SDK
MLKJapaneseTextRecognizerOptions *japaneseOptions = [[MLKJapaneseTextRecognizerOptions alloc] init];
MLKTextRecognizer *japaneseTextRecognizer = [MLKTextRecognizer textRecognizerWithOptions:options];

// When using Korean script recognition SDK
MLKKoreanTextRecognizerOptions *koreanOptions = [[MLKKoreanTextRecognizerOptions alloc] init];
MLKTextRecognizer *koreanTextRecognizer = [MLKTextRecognizer textRecognizerWithOptions:options];

2. 準備輸入圖片

將圖片以 UIImageCMSampleBufferRef 的形式傳遞至 TextRecognizerprocess(_:completion:) 方法:

使用 UIImageCMSampleBuffer 建立 VisionImage 物件。

如果您使用 UIImage,請按照下列步驟操作:

  • 使用 UIImage 建立 VisionImage 物件。請務必指定正確的 .orientation

    Swift

    let image = VisionImage(image: UIImage)
    visionImage.orientation = image.imageOrientation

    Objective-C

    MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
    visionImage.orientation = image.imageOrientation;

如果您使用 CMSampleBuffer,請按照下列步驟操作:

  • 指定 CMSampleBuffer

    如何取得圖片方向:

    Swift

    func imageOrientation(
      deviceOrientation: UIDeviceOrientation,
      cameraPosition: AVCaptureDevice.Position
    ) -> UIImage.Orientation {
      switch deviceOrientation {
      case .portrait:
        return cameraPosition == .front ? .leftMirrored : .right
      case .landscapeLeft:
        return cameraPosition == .front ? .downMirrored : .up
      case .portraitUpsideDown:
        return cameraPosition == .front ? .rightMirrored : .left
      case .landscapeRight:
        return cameraPosition == .front ? .upMirrored : .down
      case .faceDown, .faceUp, .unknown:
        return .up
      }
    }
          

    Objective-C

    - (UIImageOrientation)
      imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation
                             cameraPosition:(AVCaptureDevicePosition)cameraPosition {
      switch (deviceOrientation) {
        case UIDeviceOrientationPortrait:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored
                                                                : UIImageOrientationRight;
    
        case UIDeviceOrientationLandscapeLeft:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored
                                                                : UIImageOrientationUp;
        case UIDeviceOrientationPortraitUpsideDown:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored
                                                                : UIImageOrientationLeft;
        case UIDeviceOrientationLandscapeRight:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored
                                                                : UIImageOrientationDown;
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
          return UIImageOrientationUp;
      }
    }
          
  • 使用 CMSampleBuffer 物件和方向建立 VisionImage 物件:

    Swift

    let image = VisionImage(buffer: sampleBuffer)
    image.orientation = imageOrientation(
      deviceOrientation: UIDevice.current.orientation,
      cameraPosition: cameraPosition)

    Objective-C

     MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer];
     image.orientation =
       [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation
                                    cameraPosition:cameraPosition];

3. 處理圖片

接著,將圖片傳遞至 process(_:completion:) 方法:

Swift

textRecognizer.process(visionImage) { result, error in
  guard error == nil, let result = result else {
    // Error handling
    return
  }
  // Recognized text
}

Objective-C

[textRecognizer processImage:image
                  completion:^(MLKText *_Nullable result,
                               NSError *_Nullable error) {
  if (error != nil || result == nil) {
    // Error handling
    return;
  }
  // Recognized text
}];

4. 從已辨識的文字區塊中擷取文字

如果文字辨識作業成功,系統會傳回 Text 物件。Text 物件包含全文 已辨識在圖片中,且為零或多個 TextBlock 如需儲存大量結構化物件 建議使用 Cloud Bigtable

每個 TextBlock 都代表矩形文字區塊, 包含零個或多個 TextLine 物件。每個 TextLine 物件都包含零個或多個 TextElement 物件,這些物件代表字詞和字詞類型實體,例如日期和數字。

針對每個 TextBlockTextLineTextElement 物件,您可以在 區域的邊界座標。

例如:

Swift

let resultText = result.text
for block in result.blocks {
    let blockText = block.text
    let blockLanguages = block.recognizedLanguages
    let blockCornerPoints = block.cornerPoints
    let blockFrame = block.frame
    for line in block.lines {
        let lineText = line.text
        let lineLanguages = line.recognizedLanguages
        let lineCornerPoints = line.cornerPoints
        let lineFrame = line.frame
        for element in line.elements {
            let elementText = element.text
            let elementCornerPoints = element.cornerPoints
            let elementFrame = element.frame
        }
    }
}

Objective-C

NSString *resultText = result.text;
for (MLKTextBlock *block in result.blocks) {
  NSString *blockText = block.text;
  NSArray<MLKTextRecognizedLanguage *> *blockLanguages = block.recognizedLanguages;
  NSArray<NSValue *> *blockCornerPoints = block.cornerPoints;
  CGRect blockFrame = block.frame;
  for (MLKTextLine *line in block.lines) {
    NSString *lineText = line.text;
    NSArray<MLKTextRecognizedLanguage *> *lineLanguages = line.recognizedLanguages;
    NSArray<NSValue *> *lineCornerPoints = line.cornerPoints;
    CGRect lineFrame = line.frame;
    for (MLKTextElement *element in line.elements) {
      NSString *elementText = element.text;
      NSArray<NSValue *> *elementCornerPoints = element.cornerPoints;
      CGRect elementFrame = element.frame;
    }
  }
}

輸入圖片規範

  • 為了讓 ML Kit 準確辨識文字,輸入圖片必須包含由足夠像素資料代表的文字。理想情況下,每個字元至少應為 16 x 16 像素。一般來說 對字元大於 24x24 像素的特性來說,準確性的優勢在於。

    舉例來說,如果要掃描占據整個圖片寬度的名片,使用 640x480 的圖片可能會是個不錯的選擇。如何掃描列印的文件 則建議使用 720x1280 像素的圖片。

  • 圖片對焦不佳可能會影響文字辨識準確度。如果您無法取得可接受的結果,請嘗試要求使用者重新拍攝圖片。

  • 如果您要在即時應用程式中辨識文字,應考量輸入圖片的整體尺寸。較小 也能加快處理速度如要縮短延遲時間,請確保文字會盡量佔滿 盡可能擷取圖片,並以較低解析度拍攝圖片 (提醒您, 規定)。若需更多資訊,請參閲 提升成效的訣竅

提升成效的訣竅

  • 如要處理影像框,請使用偵測器的 results(in:) 同步 API。請從 AVCaptureVideoDataOutputSampleBufferDelegatecaptureOutput(_, didOutput:from:) 函式呼叫這個方法,以便同步取得指定影片影格中的結果。請將 AVCaptureVideoDataOutputalwaysDiscardsLateVideoFrames 設為 true,以便調節對偵測器的呼叫。如果在偵測器執行期間有新的影片影格可用,系統就會捨棄該影格。
  • 如果您使用偵測器的輸出內容,在輸入圖片上疊加圖形,請先從 ML Kit 取得結果,然後在單一步驟中算繪圖片和疊加圖形。這樣一來,您只需為每個已處理的輸入影格轉譯一次顯示介面。請參閱 updatePreviewOverlayViewWithLastFrame 也可以查看一個範例
  • 建議您以較低解析度拍攝相片。不過,請務必遵守這個 API 的圖片尺寸規定。
  • 為避免可能降低效能,請勿重複執行多個 TextRecognizer 執行個體具有不同指令碼選項。