[swift] Swift에서 카메라로 OCR(광학 문자 인식) 적용하기

Swift에서 카메라로 OCR을 적용하는 방법에 대해 알아보겠습니다.

필요한 라이브러리 설치

먼저, OCR을 적용하기 위해 GoogleMobileVision 라이브러리를 설치해야 합니다. Podfile에 다음과 같이 라이브러리를 추가해 주세요.

pod 'GoogleMLKit/TextRecognition'

그리고 터미널에서 pod install을 실행하여 라이브러리를 프로젝트에 추가하세요.

카메라 뷰 만들기

카메라 화면을 보여주기 위해 UIImagePickerController을 사용하여 카메라 뷰를 만들어 주세요. 구현 예시는 다음과 같습니다.

import UIKit

class CameraViewController: UIViewController, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    let imagePicker = UIImagePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
    }
    
    @IBAction func takePhotoButtonTapped(_ sender: UIButton) {
        present(imagePicker, animated: true, completion: nil)
    }
}

OCR 적용하기

이제, 카메라로 사진을 찍고 그 안에 있는 텍스트를 확인하고 싶을 때 GoogleMobileVision을 사용하여 OCR을 적용할 수 있습니다. 구현 예시는 다음과 같습니다.

import UIKit
import FirebaseMLVision

class OCRViewController: UIViewController {

    let textRecognizer = TextRecognizer.textRecognizer()
    
    func processImage(_ image: UIImage) {
        let visionImage = VisionImage(image: image)
        
        textRecognizer.process(visionImage) { result, error in
            guard error == nil, let result = result else {
                // Handle error
                return
            }
            for block in result.blocks {
                for line in block.lines {
                    for element in line.elements {
                        let text = element.text
                        // Process recognized text
                    }
                }
            }
        }
    }
}

이제, processImage 메서드를 호출하여 OCR을 적용한 후, 결과를 확인할 수 있습니다.

결론

Swift에서 카메라로 OCR을 적용하는 방법에 대해 알아보았습니다. GoogleMobileVisionTextRecognition 라이브러리를 사용하여 카메라로 찍은 이미지 안의 텍스트를 감지하고 처리할 수 있습니다.

관련 링크: