How do I use Vision framework for OCR and detection in Swift?

The Vision framework in Swift provides powerful tools for Optical Character Recognition (OCR) and image analysis. By leveraging this framework, developers can easily detect and extract text from images. Below is a simple example demonstrating how to use the Vision framework for OCR in Swift.

import UIKit import Vision class OCRViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() performOCR() } func performOCR() { guard let image = UIImage(named: "sampleImage") else { print("Image not found") return } // Convert UIImage to CGImage guard let cgImage = image.cgImage else { return } // Create a request to recognize text let request = VNRecognizeTextRequest { (request, error) in guard error == nil else { print("Error recognizing text: \(String(describing: error?.localizedDescription))") return } // Process recognized texts if let results = request.results as? [VNRecognizedTextObservation] { for observation in results { guard let topCandidate = observation.topCandidates(1).first else { continue } print("Recognized text: \(topCandidate.string)") } } } request.recognitionLevel = .accurate // Create a handler for the image let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) // Perform the text recognition request do { try handler.perform([request]) } catch { print("Failed to perform request: \(error)") } } }

Vision Framework OCR Optical Character Recognition Swift iOS Development Image Analysis