菜鸟IT的博客 >> Python
tesseract-ocr | python 识别图片文字
来自链接:http://t.zoukankan.com/qinlangsky-p-13491528.html
Pytesseract简介
Pytesseract是python的光学字符识别(OCR)工具。也就是说,它将识别并读取嵌入图像中的文本。 Pytesseract是Google的Tesseract-OCR引擎的包装器。它作为独立的调用脚本也很有用,因为它可以读取Python Imaging Library支持的所有图像类型,包括jpeg,png,gif,bmp,tiff等,而tesseract-ocr默认只支持tiff和bmp。
安装
安装tesseract-ocr
sudo apt-get install tesseract-ocr
安装语言库
tesseract-ocr-eng是英文库,tesseract-ocr-chi-sim是中文库
sudo apt-get install tesseract-ocr-eng tesseract-ocr-chi-sim
安装依赖及pytesseract
pytesseract是python调用谷歌tesseract-ocr工具的一个库,用于识别图片中的信息
# 安装Pillow
sudo pip3 install Pillow
# 安装pytesseract
sudo pip3 install pytesseract
使用
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
# 如果PATH中没有tesseract可执行文件,请指定tesseract路径
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'
# Example tesseract_cmd = r'/usr/share/tesseract'
# 识别的图像的字符串
print(pytesseract.image_to_string(Image.open('test.png')))
# 指定语言识别图像字符串,eng为英语
print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))
# In order to bypass the image conversions of pytesseract, just use relative or absolute image path
# NOTE: In this case you should provide tesseract supported images or tesseract will return error
print(pytesseract.image_to_string('test.png'))
# Batch processing with a single file containing the list of multiple image file paths
print(pytesseract.image_to_string('images.txt'))
# Timeout/terminate the tesseract job after a period of time
try:
print(pytesseract.image_to_string('test.jpg', timeout=2)) # Timeout after 2 seconds
print(pytesseract.image_to_string('test.jpg', timeout=0.5)) # Timeout after half a second
except RuntimeError as timeout_error:
# Tesseract processing is terminated
pass
# 获取图像边界框
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')))
# Get a searchable PDF
pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf')
with open('test.pdf', 'w+b') as f:
f.write(pdf) # pdf type is bytes by default
# Get HOCR output
hocr = pytesseract.image_to_pdf_or_hocr('test.png', extension='hocr')
示例
提取本地图片上的文字为一个整体的字符串
def get_image_string(path, filename):
'''使用谷歌开源框架ocr技术提取图片上的信息为字符串
:Param path: <str> 图片的位置
:Param filename: <str> 图片的名称
:Return : <string> 从图片中提取的字符串
'''
username = getpass.getuser()
path_base = '/home/' + str(username) + '/' + str(path) + '/' + str(filename) + '.png'
text = pytesseract.image_to_string(Image.open(path_base), lang="chi_sim").replace(" ", "").replace("
", "")
print(text)
return text
菜鸟IT博客[2022.05.10-10:47] 访问:346