如何从图片提取文字
要从图片中提取文字,可以使用光学字符识别(OCR)技术,OCR 是一种将图像中的文字转换为可编辑文本的计算机视觉技术,有许多 OCR 工具和库可以实现这一功能,如 Tesseract、Adobe Acrobat 等,以下是使用 Tesseract OCR 从图片中提取文字的简要步骤:
1、安装 Tesseract OCR:首先需要在计算机上安装 Tesseract OCR,可以访问其官方网站(https://github.com/tesseract-ocr/tesseract)下载适合自己操作系统的版本,并按照说明进行安装。
2、安装 Python 的 pytesseract 库:pytesseract 是 Tesseract OCR 的 Python 封装库,可以使用 pip 进行安装:pip install pytesseract。
3、安装 Pillow 库:Pillow 是 Python 的一个图像处理库,用于处理图片,可以使用 pip 进行安装:pip install pillow。
4、编写代码:使用以下代码从图片中提取文字。
from PIL import Imageimport pytesseractdef image_to_text(image_path): # 打开图片 img = Image.open(image_path) # 使用 Tesseract OCR 提取文字 text = pytesseract.image_to_string(img, lang='chi_sim') return text示例image_path = 'example.jpg'print(image_to_text(image_path))
5、运行代码:将上述代码保存为一个 Python 文件(如 extract_text.py),然后在命令行中运行该文件,确保图片路径(image_path)正确,且图片中包含可识别的文字。