Python-tesseract识别图片文字

郎和志
2023-12-01

介绍:Python-tesseract是python的光学字符识别(OCR)工具。也就是说,它将识别并“读取”嵌入图像中的文本。

Python-tesseract是Google的Tesseract-OCR引擎的包装器。它作为独立的调用脚本也很有用,因为它可以读取Python Imaging Library支持的所有图像类型,包括jpeg,png,gif,bmp,tiff等,而tesseract-ocr默认只支持tiff和bmp。此外,如果用作脚本,Python-tesseract将打印已识别的文本,而不是将其写入文件。

用法

快速开始

try:
    import Image
except ImportError:
    from PIL import Image
import pytesseract
#如果PATH中没有tesseract可执行文件,请包含以下内容:
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'
#示例tesseract_cmd = r'C:\ Program Files(x86)\ Tesseract-OCR \ tesseract'
#简单的图像串
print(pytesseract.image_to_string(Image.open('test.png')))
#法语文本图像串
print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))
#获取包围盒估计
print(pytesseract.image_to_boxes(Image.open('test.png')))
#获取详细的数据,包括盒,置信线和页码
print(pytesseract.image_to_data(Image.open('test.png')))
#获取有关方向和脚本检测信息
print(pytesseract.image_to_osd(Image.open('test.png'))
#为了绕过内部图像的转换,只需用相对或绝对图像路径
#注:如果你不使用支持的图像,正方体将返回错误
print(pytesseract.image_to_string('test.png'))

支持OpenCV image / NumPy数组对象

import cv2
img = cv2.imread(r'/<path_to_image>/digits.png')
print(pytesseract.image_to_string(img))
#或显式转换预先
print(pytesseract.image_to_string(Image.fromarray(img))

如果您有tessdata错误,请添加以下配置:“打开数据文件时出错......”

tessdata_dir_config  =  r ' -  tessdata-dir“<replace_with_your_tessdata_dir_path>”' 
#示例config:r' -  tessdata-dir“C:\ Program Files(x86)\ Tesseract-OCR \ tessdata”' 
#添加双引号很重要在dir路径附近。
pytesseract.image_to_string(image, lang='chi_sim', config=tessdata_dir_config)

功能

  • get_tesseract_version返回系统中安装的Tesseract版本。
  • image_to_string将图像上的Tesseract OCR运行结果返回到字符串
  • image_to_boxes返回包含已识别字符及其框边界的结果
  • image_to_data返回包含框边界,置信度和其他信息的结果。需要Tesseract 3.05+。有关更多信息,请查看Tesseract TSV文档
  • image_to_osd返回包含有关方向和脚本检测的信息的结果。

参数

image_to_data(image,lang = None,config ='', nice = 0,output_type = Output.STRING)

  • image Object,PIL Image /由Tesseract处理的图像的NumPy数组
  • lang String,Tesseract语言代码字符串
  • config String,任何其他配置为字符串,例如:config =' - psm 6'
  • nice Integer,修改Tesseract运行的处理器优先级。Windows不支持。尼斯调整了类似unix的流程的优点。
  • output_type Class属性,指定输出的类型,默认为string。有关所有支持类型的完整列表,请检查pytesseract.Output类的定义。

安装

先决条件:

  • Python-tesseract需要python 2.6+或python 3.x.
  • 您将需要Python Imaging Library(PIL)(或Pillow fork)。在Debian / Ubuntu下,这是包python-imagingpython3-imaging
  • 安装Google Tesseract OCR (有关如何在Linux,Mac OSX和Windows上安装引擎的其他信息)。你必须能够调用的Tesseract命令正方体。如果不是这种情况,例如因为tesseract不在您的PATH中,则必须更改“tesseract_cmd”变量pytesseract.pytesseract.tesseract_cmd。在Debian / Ubuntu下,您可以使用包tesseract-ocr。适用于Mac OS用户。请安装自制软件包tesseract

通过点子安装:

有关更多信息,请查看pytesseract包页面

$ ( env ) > pip install pytesseract

或者如果你安装了git:

$ ( env ) > pip install -U git + https://github.com/madmaze/pytesseract.git

从源代码安装:

$> git clone https://github.com/madmaze/pytesseract.git
$ ( env ) > cd pytesseract && pip install -U。
 类似资料: