如何从图片上提取文字

知识问答 2025-09-04 15:31:31 来源:互联网

要从图片上提取文字,可以使用光学字符识别(OCR)技术,OCR是一种将图像中的文字转换为可编辑文本的技术,有许多现成的OCR工具和库可以帮助我们实现这个目标,例如Tesseract OCR、Google Cloud Vision API等。

以下是使用Python和Tesseract OCR从图片上提取文字的简短步骤:

1、安装Tesseract OCR,在Windows、macOS或Linux上,可以从这里下载并安装:https://github.com/UB-Mannheim/tesseract/wiki

2、安装Python的pytesseract库,在命令行中运行以下命令:

pip install pytesseract

3、安装Python的Pillow库,在命令行中运行以下命令:

pip install Pillow

4、编写Python代码,使用pytesseract库从图片中提取文字,示例代码如下:

from PIL import Imageimport pytesseract指定Tesseract OCR的安装路径(仅在Windows上需要)pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'打开图片文件image = Image.open('example.jpg')使用Tesseract OCR提取图片中的文字text = pytesseract.image_to_string(image, lang='chi_sim')  # 如果图片中的文字是中文,请使用lang='chi_sim',否则使用lang='eng'输出提取到的文字print(text)

5、运行代码,观察输出结果,如果一切正常,图片中的文字应该已经被成功提取。