好的,所以我建议删去上面图片中的银行数据(如果这些是公司/人的真实陈述......)。作为一个实验,我将图像的大小调整为 3 倍(因此调整了像素坐标),并在此处做了几个部分的示例。
#!/usr/bin/env python3
import pytesseract
from PIL import Image
from pprint import pprint
with Image.open("BCA_Bank.png") as img:
img = img.resize((img.width*3, img.height*3))
# Do a binary threshold on the image to make it solid black & white
# the top two sections needed a different value than the bottom
# because of font weight.
topimg = img.convert("L").point(lambda p: 255 if p > 85 else 0).convert('1')
bottomimg = img.convert("L").point(lambda p: 255 if p > 200 else 0).convert('1')
sec1 = topimg.crop((29*3, 82*3, 358*3, 174*3))
sec2 = topimg.crop((574*3, 83*3, 749*3, 163*3))
tanggal = bottomimg.crop((41*3, 310*3, 86*3, 842*3))
keterangan1 = bottomimg.crop((107*3, 291*3, 230*3, 757*3))
keterangan2 = bottomimg.crop((239*3, 291*3, 388*3, 757*3))
# This will open all 5 sections in temporary windows as image previews
sec1.show()
sec2.show()
tanggal.show()
keterangan1.show()
keterangan2.show()
# This could be abstracted so as not to be repetetive.
sec1_text = pytesseract.image_to_string(sec1, config="--psm 6", lang="ind")
sec2_text = pytesseract.image_to_string(sec2, config="--psm 6", lang="ind")
tanggal_col = pytesseract.image_to_string(tanggal, config="--psm 4", lang="ind")
keterangan1_col = pytesseract.image_to_string(keterangan1, config="--psm 4", lang="ind")
keterangan2_col = pytesseract.image_to_string(keterangan2, config="--psm 4", lang="ind")
headers = ["SEC1", "SEC2", "TANGGAL", "KETERANGAN1", "KETERANGAN2"] #"CBG", "MUTASI", "SALDO"]
col_data = [
sec1_text.strip().splitlines(),
sec2_text.strip().splitlines()
] + [
[line.strip() for line in col.splitlines() if line]
for col in [tanggal_col, keterangan1_col, keterangan2_col]
]
pprint(dict(zip(headers, col_data)))
这只有在所有工作表的大小和结构几乎完全相同时才有效——因为.crop 调用专门从图像中选择框。
我不喜欢 pandas/numpy,所以我确信有一种更 Python 的方法可以使用这些库中的一个或两个来构造来自 tesseract 的解析数据。
*注意关于--psm 选项:
-
--psm 4 的意思是“假设有一列可变大小的文本。”
-
--psm 6 表示“假设一个统一的文本块。”
在终端中,输入 tesseract --help-psm 了解更多信息。