Created by CyanHall.com on 01/07/2021 , Last updated: 03/30/2021.
👉  github shields Star me if it’s helpful.
    // main.swift
// Created by CyanHall.com on 7/1/2021.

import Foundation
import Cocoa
import Vision

let path = CommandLine.arguments[1] as String
let inputImage = NSImage.init(contentsOfFile: path)

func ocrImage(image: NSImage) -> String {
    guard let cgImg = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
           fatalError("can't convert image")
       }
    var final = ""
    let requestHandler = VNImageRequestHandler(cgImage: cgImg)

    let request = VNRecognizeTextRequest { (result, error) in
        if let error = error {
            print("ERROR: (error)")
            return
        }
        guard let results = result.results, results.count > 0 else {
            print("No text found")
            return
        }

        for result in results {
            if let observation = result as? VNRecognizedTextObservation {
                for text in observation.topCandidates(1) {
                    // print(text.confidence)
                    // print(observation.boundingBox)
                    // print("\n")
                    final = text.string
                }
            }
        }
    }
    request.recognitionLevel = .accurate
    request.recognitionLanguages = ["en_GB"]
    do {
        // Perform the text-recognition request.
        try requestHandler.perform([request])
    } catch {
        print("Unable to perform the requests: (error).")
    }
    return final
}

let result = ocrImage(image: inputImage!)
print(result)
  
Usage:
    $ swift main.swift test.png
  

Maitained by Cyanhall.com, Copy Rights @ CC BY-NC-SA 4.0     ExcelRoadMap