導入
image_to_string は文字列だけを返しますが、実務では「どの単語が・画像のどこに・どれくらいの自信で認識されたか」が欲しくなります。それを返すのが image_to_data です。
説明
import pytesseract
from PIL import Image
from pytesseract import Output
img = Image.open("sample.png")
# 単語ごとの詳細(位置・信頼度つき)を辞書で受け取る
data = pytesseract.image_to_data(img, lang="eng", output_type=Output.DICT)
n = len(data["text"])
for i in range(n):
word = data["text"][i].strip()
conf = int(data["conf"][i]) # 信頼度 0〜100(-1 は無効)
if word and conf > 60: # 自信のある単語だけ採用
x, y, w, h = (data["left"][i], data["top"][i],
data["width"][i], data["height"][i])
print(f"{word!r} conf={conf} box=({x},{y},{w},{h})")
image_to_data(..., output_type=Output.DICT)… 単語ごとにtext(文字)・conf(信頼度)・left/top/width/height(位置)を並べた辞書を返します。conf(confidence)は 0〜100 の信頼度。しきい値(例:60)で足切りすると、あやしい認識を捨てられます。- 位置
(x, y, w, h)が分かるので、「元画像に認識結果の枠を描く」「特定の欄の値だけ抜く」といった処理ができます。
この「位置つきの結果」は、帳票から特定項目を抜き出す実務(例:合計金額の欄だけ読む)で重宝します。
演習
このレッスンは読み物です。image_to_string と image_to_data の違い——後者は「位置と信頼度」まで返す——を説明できるようにしましょう。信頼度でノイズを足切りする考え方は、後処理(第6章)につながります。