私的AI研究会 > Tesseract5

OCR アプリケーション基礎編 3

 実用的な AI開発に向けて、文字認識エンジン「Tesseract」(テッセラクト)を使用した「OCR アプリケーション」を開発する。(その3)

※ 最終更新:2022/01/28 

OCR プログラムの開発過程 3

OCR 文字列を検証する

 OCR で得られた文字列の有効性を調べる方法を考える。

  1. 文字列から数字を取り出す
    import re
    
    text = "2022年1月17日"
    result = re.findall(r"\d+", text)
    
    # 実行結果
    ['2022', '1', '17']
  2. 年月日の数値の妥当性を調べる
    import re
    import datetime
    
    yy = 2022
    mm = 1
    dd = 17
    try:
        str = datetime.date(yy, mm, dd)
        string = str.strftime('%Y/%m/%d')
    except ValueError:
        string = ''
        print('Invalid value error !!')
    
    # 実行結果
    2022/01/17
  3. 文字列から金額を取り出す
    import re
    
    texr = '\8,500'
    money = ''
    txt = text.replace(',','')
    if len(txt) > 0:
        result = re.findall(r"\d+", text)
        if len(result) == 1:
            money = str(result[0])
    
    # 実行結果
    8500
  4. 文字列の空白を取る
    import re
    
    text = '請 求 書'
    string = re.sub(r"[\u3000 \t]", "", text)
    
    # 実行結果
    請求書

CSV ファイルを扱う

 CSV ファイル作成方法を考える。

  1. CSV ファイル書き込み
    row_data = ['INDEX', '姓', '名']
    with open('sample.csv', 'w', encoding = 'utf_8_sig') as f:
        writer = csv.writer(f, lineterminator='\n')
        writer.writerow(row_data)
  2. CSV ファイル追加書き込み
    row_data = [1, '井筒', '政弘']
    with open('sample.csv', 'a', encoding = 'utf_8_sig') as f:
        writer = csv.writer(f, lineterminator='\n')
        writer.writerow(row_data)
  3. CSV ファイル読み出し
    with open('sample.csv', 'r', encoding = 'utf_8_sig') as f:
        string = f.read()
    
    print(type(string))
    print(string)
  4. CSV ファイルチェック (key = value があるかを調べる)
    with open(self.path, 'r', encoding = self.encoding) as f:
        reader = csv.DictReader(f)
        s = [row for row in reader]
        s0 = next((x for x in s if x[key] == value), None)

Step 6 OCR から得られた各項目の妥当性の検査と CSV 出力

  1. Step 5 のプログラムを拡張して OCR 結果のテキストを項目ごとにチェックし CSV ファイルとして出力する。
  2. 参照する伝票フォームは Step 4 のプログラムで作成したものを使う。フォームの登録は複数可能だが、本版では最初に登録されたフォームを使用する。
    複数フォームによる検索対応は今後のステップアップのテーマとする。
  3. 登録フォームの設定に従って、入力伝票ファイルを自動的に OCR 処理を行い最終的に CSV ファイルに出力する。
  4. 同一ファイルを入力した場合(ファイル名が同じ)は同様に処理されるが、CSV ファイルには書き込まない。(重複書き込みなし)
  5. 既に CSV 出力したファイルが存在する場合は追記される。

→ 以降「OCR アプリケーションを作る 4」へ続く

 

更新履歴

 

参考資料

 

Last-modified: 2022-02-10 (木) 13:55:45