由 CyanHall.com
创建于 2021-01-07,
上次更新:2021-03-30。
👉 如果有用请点赞。 用法:
👉 如果有用请点赞。
// 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)
$ swift main.swift test.png
更多