>>> from env_helper import info; info()
页面更新时间: 2023-12-13 11:02:37
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-15-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

3.11. 图片文字识别(OCR)

3.11.1. OCR与Tesseract介绍

将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR)。 可以实现OCR 的底层库并不多,目前很多库都是使用共同的几个底层OCR 库,或者是在上面进行定制。

Tesseract 是一个OCR 库,目前由Google 赞助(Google 也是一家以OCR 和机器学习技术闻名于世的公司)。 Tesseract 是目前公认最优秀、最精确的开源OCR 系统。

除了极高的精确度,Tesseract 也具有很高的灵活性。 它可以通过训练识别出任何字体(只要这些字体的风格保持不变就可以),也可以识别出任何Unicode 字符。

3.11.2. Tesseract的安装与使用

Tesseract的Windows安装包下载地址为: http://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-setup-4.00.00dev.exe , 下载后双击直接安装即可。 安装完后,需要将Tesseract添加到系统变量中。 在命令行中输入 tesseract -v 检查Tesseract是否安装完成且添加到系统变量中。

Debian / Ubuntu 用户可以通过 apt-get 安装, Debian 10, Debian 11, Ubuntu 22.04, Debian 12 验证通过:

sudo apt install tesseract-ocr tesseract-ocr-chi-sim python3-tesserocr
以下为原来方法: 这一节介绍的库名称为 pytesseract 。 pytesseract是Tesseract关于Python的接口,还需要一个Python的图片处理模块,可以安装pillow。 使用下面命令安装完后,就可以使用Python调用Tesseract了: pip install pytesseract
import pytesseract

目前使用 python3-tesserocr 。由于其本身在 Debian / Ubuntu 仓储库中,成熟度更高,推荐使用。 另外不管是 python3-tesserocr 还是 pytesseract ,都是对 Tesseract 的封装, 使用上稍有区别,没有实质的不同。

使用下面代码导入模块:

>>> import tesserocr

3.11.3. 识别示例1

用Tesseract可以识别格式规范的文字,主要具有以下特点:

  • 使用一个标准字体(不包含手写体、草书,或者十分“花哨的”字体)

  • 虽然被复印或拍照,字体还是很清晰,没有多余的痕迹或污点

  • 排列整齐,没有歪歪斜斜的字

  • 没有超出图片范围,也没有残缺不全,或紧紧贴在图片的边缘

下面将给出几个tesseract识别图片中文字的例子。

如下图:

aocr1

图 3.1 aocr1

>>> from PIL import Image
>>> text = tesserocr.image_to_text(Image.open('./ocra1.jpg'))
>>> print(text)
BREAKING THE STATUE

i have always known

i just didn't understand
the inner conflictions
arresting our hands
gravitating close enough
expansive distamce between
i couldn't give you more
but 1 meant everything
when the day comes

you find your heart

wants something more

than a viece and a part
your life will change
like astatue set free

to walk among us

to created estiny

we didn't break any rules
we didn't make mistakes
making beauty in loving
making lovine for days—

SHILOW

3.11.4. 识别示例2

接着是稍微有点倾斜的文字图片th.jpg,识别情况如下:

可以看到识别的情况不如刚才规范字体的好,但是也能识别图片中的大部分字母。

bocr2

图 3.2 bocr2

>>> test  = tesserocr.image_to_text(Image.open('./ocrb2.jpg'))
>>> test
'Vieare!n'

3.11.5. 识别中文示例

最后是识别简体中文, Windows 系统中需要事先安装简体中文语言包, 下载地址为:https://github.com/tesseract-ocr/tessdata/find/master/chi_sim.traineddata , 再将 chi_sim.traineddata 放在 C:\Program Files (x86)\Tesseract-OCR\tessdata 目录下。我们以图片为例:

示例图片:

cocr3

图 3.3 cocr3

输入命令:

tesseract timg.jpg timg.txt -l chi_sim

然后看一下在 Python 中的使用:

>>> text = tesserocr.image_to_text(
>>>     Image.open('./ocrc3.jpg'),
>>>     lang = 'chi_sim')

识别结果如下: 只识别错了一个字,识别率还是不错的。

>>> print(text)
长相思
【清】纳兰性德
山一程,水一程。身向榆
关那畔行,夜深干帐灯。
风一更,雪一更。联碎乡
心梦不成,故园无此声。

最后加一句,Tesseract对于彩色图片的识别效果没有黑白图片的效果好。