在Python中使用pytesseract识别中文图片文字的步骤详解
发布时间:2023-12-25 04:54:24
在Python中使用pytesseract识别中文图片文字的步骤如下:
1. 安装Tesseract OCR:Tesseract是一个开源的OCR引擎,可以用于识别图片中的文字。你可以从https://github.com/tesseract-ocr/tesseract 下载最新的版本,或者使用以下命令在Ubuntu系统中安装:
sudo apt-get install tesseract-ocr sudo apt-get install libtesseract-dev
2. 安装pytesseract库:pytesseract是一个Python封装的Tesseract OCR API,可以方便地在Python中使用Tesseract进行文字识别。你可以使用pip命令进行安装:
pip install pytesseract
3. 安装Pillow库:Pillow是一个Python图像处理库,可以用于打开、操作和保存图片文件。我们需要使用Pillow来打开图片文件并将其传递给pytesseract进行识别。你可以使用pip命令进行安装:
pip install pillow
4. 导入所需的库:
import pytesseract from PIL import Image
5. 打开图片文件:
image = Image.open('image.png')
6. 使用pytesseract进行文字识别:
text = pytesseract.image_to_string(image, lang='chi_sim')
这里的lang='chi_sim'表示使用简体中文模型进行识别。你可以根据需要选择其他语言模型,或者使用lang='chi_tra'来识别繁体中文。
7. 打印识别出的文字:
print(text)
你也可以将识别结果保存到文件中:
with open('output.txt', 'w', encoding='utf-8') as file:
file.write(text)
以下是一个完整的示例代码:
import pytesseract
from PIL import Image
# 打开图片文件
image = Image.open('image.png')
# 使用pytesseract进行文字识别
text = pytesseract.image_to_string(image, lang='chi_sim')
# 打印识别出的文字
print(text)
# 将识别结果保存到文件中
with open('output.txt', 'w', encoding='utf-8') as file:
file.write(text)
运行以上代码,将会对名为image.png的图片文件进行中文文字识别,并将识别结果打印出来,同时保存到名为output.txt的文本文件中。
以上就是在Python中使用pytesseract识别中文图片文字的详细步骤。你可以根据自己的需求进行适当的调整和修改。
