【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对于彩色图片的识别效果没有黑白图片的效果好。

相关推荐
IVEN_6 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang8 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮8 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling8 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮11 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽11 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers