macOS:如何从 AppleScript/JXA 访问实时文本 OCR 功能?

ccp*_*zza 4 macos applescript osascript livetext

从 macOS Monterey 开始,可以在预览中选择图像中的文本。

AppleScript 和/或 JXA(自动化 JavaScript)是否可以使用此 OCR 功能?

在此输入图像描述

Script Editor.app File>Open dictionary...我选择了Preview.app并查看了Standard SuiteText Suite的 API ,但似乎没有任何与 OCR 相关的内容。(文本套件显然与在图片上绘制文本有关,而不是与文本提取有关。)

我还在 Automator.app 中搜索了文本识别操作,但没有看到任何合适的内容。

Ste*_*lan 6

您可以使用 AppleScriptObjC 和 Vision 框架从图像中提取文本。整个过程是获取图像数据、设置所需类型的图像请求(在本例中为 VNRecognizeTextRequest)、创建相应的图像处理程序、执行请求并返回结果文本字符串。

use framework "Vision"

on getImageText(imagePath)
    -- Get image content
    set theImage to current application's NSImage's alloc()'s initWithContentsOfFile:imagePath

     -- Set up request handler using image's raw data
    set requestHandler to current application's VNImageRequestHandler's alloc()'s initWithData:(theImage's TIFFRepresentation()) options:(current application's NSDictionary's alloc()'s init())
    
    -- Initialize text request
    set theRequest to current application's VNRecognizeTextRequest's alloc()'s init()
  
     -- Perform the request and get the results
    requestHandler's performRequests:(current application's NSArray's arrayWithObject:(theRequest)) |error|:(missing value)
    set theResults to theRequest's results()

    -- Obtain and return the string values of the results
    set theText to {}
    repeat with observation in theResults
        copy ((first item in (observation's topCandidates:1))'s |string|() as text) to end of theText
    end repeat
    return theText
end getImageText

on run (argv)
    if (count of argv) is 0 then error "Must provide an image path"
    getImageText(item 1 of argv)
end run
Run Code Online (Sandbox Code Playgroud)

您可以在脚本编辑器中运行它 - 只需确保更新文件路径即可。