LoginSignup
8
5

More than 5 years have passed since last update.

スクリーンショットでOCR

Last updated at Posted at 2017-08-29

手軽にOCRできるよう、スクリーンショットからテキスト化してみました。
APIへの実行コードはGoogle Cloud Vision APIのOCR(画像認識)を検証するを利用させていただきました。ありがとうございます。

準備

サンプルファイルにAPIキーを設定後、下記コードの実行ファイル保存フォルダのパスをご自身の環境にあわせて書き換えてください。

実行するとキャプチャするアイコンになりますので(shift+command+4と同じ)、テキスト化したいエリアを選択してください。

保存フォルダにキャプチャしたpng画像とテキストファイルが保存されていると思います。

さて、このままスクリプトエディタで実行していては使い勝手がよくないですよね。
AutomatorにはAppleScriptを実行というコマンドが用意されていますのでこれでサービスつくりショートカットを割り当てましょう!

コード

on run
    my main()
end run

on main()
    --実行ファイル
    set OCR to quoted form of "/Users/9999/Desktop/GOCR/OCR.php"
    --保存フォルダ
    set saveFolder to "/Users/9999/Desktop/GOCR/"


    --pngファイル生成
    set {pngName, pngFile} to my capture(saveFolder)

    try
        (pngFile as POSIX file) as alias
    on error
        error number -128
    end try

    --テキストパス生成
    set ocrPath to my ocrTxtPath(saveFolder)

    --shellコマンド
    set cmd to "php " & OCR & space & quoted form of pngFile & " > " & quoted form of ocrPath

    --OCR実行
    set res to do shell script cmd

end main

on capture(saveFolder)
    set ssName to "ss_" & (do shell script "date +%Y%m%d_%H%M%S") & ".png"

    set savePath to saveFolder & ssName

    set cmd to "screencapture -r -x -t png -s -o " & quoted form of savePath
    do shell script cmd

    return {ssName, savePath}

end capture


on ocrTxtPath(saveFolder)
    tell application "Finder"
        set DateTime to do shell script "date +%Y%m%d_%H%M%S"
        set ocrPath to saveFolder & "OCR_" & DateTime & ".txt"
    end tell
    return ocrPath
end ocrTxtPath


on Delimiters(theText, serchStr, replaceStr)
    set OriginalDelimiters to AppleScript's text item delimiters
    set AppleScript's text item delimiters to serchStr
    set theText to text items of theText
    set AppleScript's text item delimiters to replaceStr
    set theText to theText as string
    set AppleScript's text item delimiters to OriginalDelimiters
    return theText
end Delimiters

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5