Python 中怎么识别图片里的文字

在 Python 中,我们可以使用第三方库来识别图片中的文字,最常用的是使用 Tesseract OCR 引擎。Tesseract 是一个开源的 OCR 引擎,可以识别多种语言的文字,并且支持多种操作系统。

1. 安装 Tesseract OCR 引擎

要在 Python 中使用 Tesseract OCR 引擎,首先需要安装 Tesseract。具体安装步骤可以参考 Tesseract 的官方文档:https://github.com/tesseract-ocr/tesseract

# 使用pip安装pytesseract
pip install pytesseract

# 使用apt-get工具安装tesseract
apt-get install tesseract-ocr
Python

2. 使用 pytesseract 库识别图片中的文字

安装完 Tesseract 之后,我们可以使用 pytesseract 库来调用 Tesseract 的功能。

import pytesseract
from PIL import Image

# 打开图片
image = Image.open('image.jpg')

# 使用 pytesseract 库识别图片中的文字
text = pytesseract.image_to_string(image, lang='eng')

# 打印识别的文字
print(text)
Python

3. 参数调整和文字预处理

在使用 pytesseract 识别图片中的文字时,我们可以通过调整一些参数和进行文字预处理来提高识别准确率。比如可以使用 image_to_string 函数的 config 参数来设定一些识别参数,或者使用图像处理技术来对图片进行预处理,如灰度化、二值化、去噪等。

# 设定识别参数
config = '--psm 6'

# 对图片进行灰度化和二值化处理
gray = image.convert('L')
bw = gray.point(lambda x: 0 if x < 150 else 255, '1')

# 使用 pytesseract 库识别处理后的图片中的文字
text = pytesseract.image_to_string(bw, config=config)

# 打印识别的文字
print(text)
Python