\

Pythonは、その柔軟性と強力なライブラリエコシステムのおかげで、OCR(光学式文字認識)のようなタスクに非常に適しています。特に、オープンソースのOCRツールをPythonで利用することで、画像からテキストを抽出することが可能になります。

Surya: 多言語対応のOCRツール

Suryaは、オープンソースで提供される多言語対応のOCRツールです。特にテーブルとチャートの検出が可能で、その機能は個人的に非常に期待できるものです。開発者はVik Paruchuriで、ライセンスはGNU General Public License v3.0です。

from PIL import Image,ImageDraw
import matplotlib.pyplot as plt
from surya.detection import batch_inference
from surya.model.segformer import load_model, load_processor

# 画像に対してバウンディングボックスを描画する関数
def draw_boxes(image, boxes):
    draw = ImageDraw.Draw(image)
    for box in boxes:
        draw.rectangle(box, outline="red", width=2)
    return image

IMAGE_PATH = "画像のpath"

image = Image.open(IMAGE_PATH)
model, processor = load_model(), load_processor()

# predictions is a list of dicts, one per image
predictions = batch_inference([image], model, processor)

print(predictions)

# バウンディングボックスの座標を取得
boxes = predictions[0]['bboxes']

# 画像にバウンディングボックスを描画
image_with_boxes = draw_boxes(image.copy(), boxes)

# 描画した画像を表示
plt.imshow(image_with_boxes)
plt.show()

Tesseractとpytesseract

TesseractはオープンソースのOCRエンジンで、PythonでOCRを実装するためには、このTesseractと、それをPythonで使えるようにしたライブラリであるpytesseractを使用します。

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タスクにおいて有用です。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です