PythonでOCR(Optical Character Recognition)を実装するためには、TesseractというオープンソースのOCRエンジンと、それをPythonで使えるようにしたライブラリであるpytesseractを使用します。
Tesseractとpytesseractのインストール
まずは、Tesseractとpytesseractをインストールする必要があります。Tesseractは以下からインストールできます。
- Windows: UB MannheimのGitHubページ
- macOS:
brew install tesseract
- Linux:
sudo apt install tesseract-ocr
次に、pytesseractとPillowをインストールします。以下のコマンドを実行します。
pip install pytesseract Pillow
画像から文字を読み取る
以下のPythonソースコードは、画像から文字を読み取るサンプルです。
import sys
import pytesseract
from PIL import Image
def image_to_text(image_path):
# 画像を読み込む
img = Image.open(image_path)
# TesseractでOCRを実行
text = pytesseract.image_to_string(img, lang='jpn')
return text
if __name__ == "__main__":
if len(sys.argv) > 1:
image_path = sys.argv[1] # コマンドライン引数から画像ファイルのパスを取得
text = image_to_text(image_path)
print(text)
else:
print("Usage: python app.py <path_to_image>")
このコードを実行すると、指定した画像の文字を読み取り、その結果を出力します。
以上がPythonとOCRを用いて画像から文字を読み取る基本的な方法です。さまざまな応用が可能なので、ぜひ試してみてください。.