【Python】Python 图片文字识别(OCR)-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

Python 图片文字识别OCR

1. OCR与Tesseract介绍

将图片翻译成文字一般被称为光学文字识别Optical Character RecognitionOCR。可以实现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对于彩色图片的识别效果没有黑白图片的效果好。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: python