
Pythonで
画像ファイル内のテキストを・・・


抽出できます!
※OCRできます。
※精度はそこそこです。


バッチファイルから
・無料のOCRエンジン「tesseract-ocr」
を実行することで実現します!
※「tesseract-ocr」のインストールが必要です。
tesseract-ocrのダウンロードとインストール
以下の記事の「tesseract-ocrのダウンロード」と「tesseract-ocrのインストール」をご確認ください。
Pythonライブラリのインストール
サードパーティのPythonライブラリである以下2つをインストールします。
・pytesseract
・Pillow
pip install pytesseract Pillow
コード
ここでは例として
・デスクトップ配下の画像ファイル「sample_gazou.png」から
・テキストを抽出
します。
※テキストファイルを出力します。

from PIL import Image
import pytesseract
# Tesseract OCRの実行ファイル
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
# 画像ファイル
image_path = r"C:\Users\lunch\Desktop\sample_gazou.png"
# 出力ファイル
output_file = r"C:\Users\lunch\Desktop\output.txt"
# 画像を開く
image = Image.open(image_path)
# 画像から文字を抽出
text = pytesseract.image_to_string(image, lang="jpn")
# 結果をファイル出力
with open(output_file, "w", encoding="shift_jis") as file:
file.write(text)
実行結果
画像ファイル内のテキストを抽出できました。
※テキストファイルを出力できました。



参考
上記で使用した以下の詳細は、公式サイトをご確認ください。
●サードパーティのPythonライブラリ「PIL(Pillow)」の「Image」モジュール
●サードパーティのPythonライブラリ「pytesseract」