"""
OCR_imageモジュール
このモジュールは、Tesseract OCRを利用して画像ファイルからテキストを抽出するための機能を提供します。
指定された画像ファイルパスと言語設定に基づき、文字認識処理を実行し、結果のテキストを返します。
関連リンク: :doc:`OCR_image_usage`
"""
#Tesseract OCR for Windows: https://tesseract-ocr.github.io/tessdoc/Downloads.html
# tessdata/jpn.traineddata が必要
# pip install Pillow PyMuPDF pytesseract
import os
import sys
from PIL import Image
import pytesseract
image_file = "IMG_8583.jpg" # 実際の画像ファイル名に置き換えてください
[ドキュメント]
def ocr_from_image(image_path, lang='jpn'):
"""
画像ファイルから文字認識を行い、抽出されたテキストを返します。
詳細説明:
Pillowライブラリを使用して画像を読み込み、pytesseractを用いてOCR処理を実行します。
ファイルが見つからない場合や、OCR処理中に何らかのエラーが発生した場合は、
適切なエラーメッセージを文字列として返します。
:param image_path: str: OCR処理を行う画像ファイルへのパス。
:param lang: str: OCRエンジンが認識に使用する言語。
'jpn' (日本語) や 'eng' (英語) などの言語コードを一つ、
または 'jpn+eng' のように '+' で複数指定できます。
デフォルトは 'jpn' です。
:returns: str: 画像から抽出されたテキスト。ファイルが見つからない場合や
OCR処理中にエラーが発生した場合は、エラーメッセージ。
"""
try:
img = Image.open(image_path)
text = pytesseract.image_to_string(img, lang=lang)
return text
except FileNotFoundError:
return f"エラー: ファイル '{image_path}' が見つかりません。"
except Exception as e:
return f"OCR処理中にエラーが発生しました: {e}"
if __name__ == "__main__":
if not os.path.exists(image_file):
# テスト用のダミー画像ファイルを作成 (実際には既存の画像を使用してください)
try:
# Pillowを使って簡単なダミー画像を生成
from PIL import ImageDraw, ImageFont
img = Image.new('RGB', (400, 200), color = (255, 255, 255))
d = ImageDraw.Draw(img)
try:
# フォントのパスはシステムによって異なる場合があります
font = ImageFont.truetype("arial.ttf", 30) # Windowsの場合の例
except IOError:
font = ImageFont.load_default() # デフォルトフォントを使用
d.text((50, 50), "これはテスト画像です。", fill=(0, 0, 0), font=font)
d.text((50, 100), "Hello, OCR!", fill=(0, 0, 0), font=font)
img.save(image_file)
print(f"ダミー画像 '{image_file}' を作成しました。")
except Exception as e:
print(f"ダミー画像の作成に失敗しました: {e}")
print("既存の画像ファイルを使用するか、手動で画像ファイルを作成してください。")
print(f"\n--- 画像ファイル '{image_file}' のOCR結果 ---")
extracted_text_image = ocr_from_image(image_file, lang='jpn+eng')
print(extracted_text_image)