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)")
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?