温馨提示×

python怎么提取图片文字

小亿
131
2023-12-07 23:07:35
栏目: 编程语言

要提取图片中的文字,可以使用Python的OCR(Optical Character Recognition,光学字符识别)库。以下是使用tesseract库进行图片文字提取的示例代码:

  1. 首先,确保已经安装了tesseract OCR库和Python的tesseract库。可以使用以下命令进行安装:
pip install tesseract
pip install pytesseract
  1. 导入所需的库:
import pytesseract
from PIL import Image
  1. 加载并预处理图片:
image = Image.open('image.jpg')  # 加载图片
image = image.convert('L')  # 转为灰度图像
  1. 使用tesseract进行文字提取:
text = pytesseract.image_to_string(image)
print(text)

运行以上代码后,将会输出提取到的图片文字。

需要注意的是,以上代码使用的是tesseract的默认语言模型进行文字提取。如果需要提取特定语言的文字,可以使用pytesseract.image_to_string函数的lang参数指定语言模型,例如:

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

此外,要使用tesseract进行文字提取,还需要将tesseract的可执行程序路径添加到系统环境变量中,或者在代码中指定tesseract的可执行程序路径。

0