To perform OCR (Optical Character Recognition) on multiple images in Swift, you can utilize the Text Vision Kit and process each image individually. Here's an example of how you can perform OCR on multiple images:
Set up the necessary imports and a function to handle OCR:
import Vision
func performOCR(on image: UIImage, completion: @escaping (String?) -> Void) {
let textRecognitionRequest = VNRecognizeTextRequest { (request, error) in
guard let observations = request.results as? [VNRecognizedTextObservation] else {
completion(nil)
return
}
var recognizedText = ""
for observation in observations {
guard let topCandidate = observation.topCandidates(1).first else { continue }
recognizedText += topCandidate.string + "\n"
}
completion(recognizedText)
}
textRecognitionRequest.recognitionLevel = .accurate
textRecognitionRequest.usesLanguageCorrection = true
guard let cgImage = image.cgImage else {
completion(nil)
return
}
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
do {
try handler.perform([textRecognitionRequest])
} catch {
completion(nil)
}
}
Prepare an array of UIImage objects representing the images you want to perform OCR on:
let images: [UIImage] = [
UIImage(named: "image1")!,
UIImage(named: "image2")!,
]
Create a dispatch group to track the completion of OCR for each image:
let group = DispatchGroup()
var recognizedTexts: [String?] = []
for image in images {
group.enter()
performOCR(on: image) { recognizedText in
recognizedTexts.append(recognizedText)
group.leave()
}
}
group.notify(queue: .main) {
for (index, text) in recognizedTexts.enumerated() {
if let recognizedText = text {
print("Image \(index + 1):")
print(recognizedText)
} else {
print("OCR failed for Image \(index + 1)")
}
}
}