技能备份 - 2026-04-15 (40个技能)

This commit is contained in:
root
2026-04-15 18:53:15 +08:00
parent f62f14814f
commit c65fce24e4
791 changed files with 190773 additions and 0 deletions
@@ -0,0 +1,70 @@
import Foundation
import Vision
import AppKit
// Swift 5.9+ CommandLine.arguments
let args = ProcessInfo.processInfo.arguments
guard args.count >= 2 else {
print("Usage: swift macvision_swift.swift <image_path>")
exit(1)
}
let imagePath = args[1]
// 1.
guard let image = NSImage(contentsOfFile: imagePath) else {
print("❌ 无法加载图片: \(imagePath)")
exit(1)
}
// 2. CGImageVision
guard let tiffData = image.tiffRepresentation,
let cgImage = NSBitmapImageRep(data: tiffData)?.cgImage else {
print("❌ 无法转换图片")
exit(1)
}
// 3.
let semaphore = DispatchSemaphore(value: 0)
var results: [(text: String, confidence: Float)] = []
// 4. OCR
let request = VNRecognizeTextRequest { request, error in
defer { semaphore.signal() } //
if let error = error {
print("❌ 识别错误:\(error)")
return
}
guard let observations = request.results as? [VNRecognizedTextObservation] else {
print("❌ 无结果")
return
}
for observation in observations {
guard let candidate = observation.topCandidates(1).first else { continue }
results.append((candidate.string, candidate.confidence))
}
}
// 5.
request.recognitionLanguages = ["zh-Hans", "zh-Hant", "en-US"] //
request.usesLanguageCorrection = true //
// 6.
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
do {
try handler.perform([request])
_ = semaphore.wait(timeout: .now() + 30) // 30
//
for (text, conf) in results {
print("文本:\(text)")
print("置信度:\(String(format: "%.2f", conf * 100))%")
}
} catch {
print("❌ 执行错误:\(error)")
}