欢迎访问宙启技术站
智能推送

Python中使用pytesseract将图片中的中文文字提取出来的代码

发布时间:2023-12-26 08:30:37

在Python中使用pytesseract库提取图片中的中文文字,需要先安装pytesseract和tesseract OCR引擎,并将tesseract的可执行文件路径配置到系统环境变量中。

1. 安装pytesseract库和tesseract引擎:

pip install pytesseract

2. 下载并安装tesseract OCR引擎:

- Windows系统,从https://github.com/UB-Mannheim/tesseract/wiki 下载并安装最新版的tesseract OCR引擎。

- MacOS系统,可以使用brew安装:

     brew install tesseract
     

- Linux系统,根据不同发行版使用相应的包管理器安装:

     sudo apt-get install tesseract-ocr
     # 或者
     sudo yum install tesseract-ocr
     

3. 导入pytesseract库和PIL库:

import pytesseract
from PIL import Image

4. 加载图片:

image = Image.open('image.png')  # 替换为实际的图片路径

5. 使用pytesseract库提取中文文字:

text = pytesseract.image_to_string(image, lang='chi_sim')
print(text)

完整的实例代码如下:

import pytesseract
from PIL import Image

# 加载图片
image = Image.open('image.png')  # 替换为实际的图片路径

# 提取中文文字
text = pytesseract.image_to_string(image, lang='chi_sim')

print(text)

上述代码将图片中的中文文字提取出来,并打印输出。根据具体的图片和识别结果,可能需要选择适当的调参或使用其他方法提高提取效果。在使用pytesseract提取中文文字时,可以指定lang='chi_sim'参数来使用简体中文语言。