\

Pythonは、画像やPDFからテーブルデータを抽出するための強力なツールを提供しています。特に、OCR(Optical Character Recognition)は、画像からテキストを読み取るための重要な技術です。

テーブルOCRの基本

テーブルOCRは、画像やPDFからテーブルデータを抽出するプロセスです。これは、特に複数の列を持つデータ(例えば、スプレッドシートやテーブルなど)をOCRする際に重要となります。

しかし、テーブルのOCRはいくつかの問題を抱えています。例えば、Tesseractはノイズの多い画像に対する多列OCRが得意ではありません。また、OCRエンジンはテキストを正しくOCRできるかもしれませんが、テキストを列/行に関連付けることができないかもしれません。

PythonでのテーブルOCR

Pythonでは、pytesseractpdf2imageなどのライブラリを使用して、画像やPDFからテーブルデータを抽出することができます。また、tablecvはPaddleOCRを使用してテーブルを抽出し、pandas DataFrameオブジェクトを返す方法を提供しています。

以下に、PythonでテーブルOCRを行う基本的なコードスニペットを示します。

from pdf2image import convert_from_path
import pytesseract
from PIL import Image
import os
import re
from datetime import datetime

# Tesseract OCRの実行ファイルへのパスを設定
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

input_dir = r"C:\\Users\\_\\Documents\\Python\\OCR\\Input"
output_dir = r"C:\\Users\\_\\Documents\\Python\\OCR\\output"

# 今日の日付を取得し、日付のフォルダを作成
today = datetime.now().strftime("%Y%m%d")
today_output_dir = os.path.join(output_dir, today)
if not os.path.exists(today_output_dir):
    os.makedirs(today_output_dir)

dpi = 300
mm_to_pixel = dpi / 25.4

pdf_files = [file for file in os.listdir(input_dir) if file.endswith('.pdf')]
file_counter = 1

for pdf_file in pdf_files:
    pdf_path = os.path.join(input_dir, pdf_file)
    images = convert_from_path(pdf_path, dpi=dpi)

    for page_number, image in enumerate(images, start=1):
        width, height = image.size

        # 左下の領域を指定(横12cm、縦2cm)
        x = 120 * mm_to_pixel
        y = 20 * mm_to_pixel
        area = (0, height - y, x, height)

        # 左下の領域を計算
        # OCR用の画像を切り取る
        cropped_image = image.crop(area)

        # 切り取った画像からテキストを読み取る
        text = pytesseract.image_to_string(cropped_image, lang='jpn').strip()

        # 読み取ったテキストを基にファイル名を生成
        if text:
            base_filename = re.sub(r'[\\\\/*?:\"<>|]', "", text.splitlines()[0])[:15]
        else:
            base_filename = "no_text"

        filename = f"{file_counter}_{base_filename}_{today}"
        unique_filename = f"{filename}_1.pdf"
        counter = 1

        while os.path.exists(os.path.join(today_output_dir, unique_filename)):
            counter += 1
            unique_filename = f"{filename}_{counter}.pdf"

        file_path = os.path.join(today_output_dir, unique_filename)

        # 元の画像全体をPDFとして保存
        image.save(file_path, "PDF", resolution=dpi)

        print(f"PDF saved as  {file_path}")

        file_counter += 1

このコードは、PDFから特定の領域のテキストを抽出し、抽出したテキストを基にファイル名を生成してPDFを保存するPythonスクリプトです。

Pythonを使用したテーブルOCRは、データ分析や自動化タスクにおいて非常に有用です。適切なツールとテクニックを使用すれば、画像やPDFからテーブルデータを効率的に抽出することが可能です。

投稿者 admin

コメントを残す

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