以下の出典で勉強しました。
■出典
(基本操作) https://gammasoft.jp/blog/tesseract-ocr-install-on-windows/
(画像加工) https://gammasoft.jp/blog/ocr-by-python/
(オプション類) https://qiita.com/henjiganai/items/7a5e871f652b32b41a18
■参考コード
#出典(基本操作) https://gammasoft.jp/blog/tesseract-ocr-install-on-windows/
#出典(画像加工) https://gammasoft.jp/blog/ocr-by-python/
#出典(オプション類) https://qiita.com/henjiganai/items/7a5e871f652b32b41a18
# be ready libraries as bellows:
# tesseract download from url as bellow ,and install it with check additional language at japanese and so on.
# https://github.com/UB-Mannheim/tesseract/wiki
# pip install pyocr
# pip install pillow
# see tesseract options as bellow;
# https://github.com/tesseract-ocr/tesseract/blob/main/doc/tesseract.1.asc
import os
from PIL import Image
import pyocr
#【基本手順1】 環境変数「PATH」にTesseract-OCRのパスを設定。Windowsの環境変数に設定している場合は不要。
path='C:/Program Files/Tesseract-OCR/'
os.environ['PATH'] = os.environ['PATH'] + path
#【基本手順2】pyocrにTesseractを指定する。
pyocr.tesseract.TESSERACT_CMD = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
tools = pyocr.get_available_tools()
tool = tools[0]
#【基本手順3-1】 文字を抽出したい画像のパスを選ぶ
#img = Image.open('C:/Users/shienkikou11/Desktop/test2048.png')
#img = Image.open('C:/Users/shienkikou11/Desktop/ocr-test.png')
img_org = Image.open('C:/Users/shienkikou11/Desktop/zairyucard_omote.jpg')
#【基本手順3-2】 原稿画像加工(黒っぽい色以外は白=255,255,255に置き換える。しきい値をc_maxで指定)
img_rgb = img_org.convert("RGB")
pixels = img_rgb.load()
c_max = 169
for j in range(img_rgb.size[1]):
for i in range(img_rgb.size[0]):
if (pixels[i, j][0] > c_max or pixels[i, j][1] > c_max or
pixels[i, j][0] > c_max):
pixels[i, j] = (255, 255, 255)
#【基本手順4】画像の文字を抽出
#レイアウトオプション番号と説明
#0 文字角度の識別と書字系のみの認識(OSD)のみ実施(outputbase.osdが出力され、OCRは行われない)
#1 OSDと自動ページセグメンテーション
#2 OSDなしの自動セグメンテーション(OCRは行われない)
#3 OSDなしの完全自動セグメンテーション(デフォルト)
#4 可変サイズの1列テキストを想定する
#5 縦書きの単一のテキストブロックとみなす
#6 単一のテキストブロックとみなす(5と異なる点は横書きのみ)
#7 画像を1行のテキストとみなす
#8 画像を単語とみなす
#9 円の中に記載された1単語とみなす(例:①、⑥など)
#10 画像を1文字とみなす
#11 まだらなテキスト。特定の順序でなるべく多くの単語を検出する(角度無し)
#12 文字角度検出を実施(OSD)しかつ、まだらなテキストとしてなるべく多くの単語を検出する
#13 Tesseract固有の処理を回避して1行のテキストとみなす
#レイアウトオプションを設ける場合
#builder = pyocr.builders.TextBuilder(tesseract_layout=6)
#レイアウトオプションなしの場合
builder = pyocr.builders.TextBuilder()
#言語オプションの設定
#日本語 lang="jpn"
#英語 lang="eng"
#簡体字 lang="chi_sim"
#繁体字 lang="chi_tra"
#元画像での文字化
#text = tool.image_to_string(img_org , lang="jpn", builder=builder)
#RGB処理済画像での文字化
text = tool.image_to_string(img_rgb , lang="jpn", builder=builder)
print(text)