【Python】Python 图片文字识别(OCR)

Python 图片文字识别(OCR)

1. OCR与Tesseract介绍

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

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

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

2. Tesseract的安装与使用

Tesseract的Windows安装包下载地址为: http://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-setup-4.00.00dev.exe ,下载后双击直接安装即可。安装完后,需要将Tesseract添加到系统变量中。在CMD中输入tesseract -v, 如显示以下界面,则表示Tesseract安装完成且添加到系统变量中。

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

sudo apt install tesseract-ocr tesseract-ocr-chi-sim python3-tesserocr

但是要注意 python3-tesserocr 并非是下面要介绍的。这一节介绍的库名称为 pytesseract 。 pytesseract是Tesseract关于Python的接口,还需要一个Python的图片处理模块,可以安装pillow。 使用下面命令安装完后,就可以使用Python调用Tesseract了:

pip install pytesseract

import pytesseract

3. 识别示例1

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

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

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

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

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

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

from PIL import Image

text = pytesseract.image_to_string(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

4. 识别示例2

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

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

text = pytesseract.image_to_string(Image.open('./ocrb2.jpg'))

text

'Vieare!n'

3.11.5. 识别示例3

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

输入命令:

tesseract timg.jpg timg.txt -l chi_sim

示例图片:

text = pytesseract.image_to_string(

Image.open('./ocrc3.jpg'),

lang = 'chi_sim')

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

长相思

【清】纳兰性德

山一程,水一程。身向榆

关那畔行,夜深干帐灯。

风一更,雪一更。联碎乡

心梦不成,故园无此声。

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

相关推荐
用户8356290780511 分钟前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生8 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师8 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码8 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf9 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python