Python实现OCR图像识别:Tesseract与PIL基础用法
本文介绍利用Python进行图像识别的两种常见方法。首先展示使用Pillow和pytesseract库直接读取图片并转换为文本的示例,涵盖灰度处理逻辑。其次介绍通过命令行调用系统Tesseract引擎的高级封装方式,支持中文识别、参数配置及文件清理机制。内容适用于需要轻量级OCR解决方案的开发者参考。
Python图像识别实现概述
本文分享使用Python实现图像识别功能的具体代码示例,供读者参考学习。
基于PIL与pytesseract的基础识别
#! /usr/bin/env python
from PIL import Image
import pytesseract
url='img/denggao.jpeg'
image=Image.open(url)
#image=image.convert('RGB') # RGB
image=image.convert('L') # 灰度
image.load()
text=pytesseract.image_to_string(image)
print text
#image.show()
r'''''#
zhongwen_url = 'img/zhongwen003.png'
import os
fn = "aaaa"
# sudo apt-get install tesseract
cmd = "tesseract " + zhongwen_url + " " + fn + " -l chi_sim"
os.system(cmd)
with open(fn+".txt", "r") as f:
print f
ret=os.system('cat /etc/pam.conf')
print ret
print '----------------------'
ret=os.popen('cat /etc/pam.conf')
print ret'''
r'''''
import os
import subprocess
def image_to_string(img, cleanup=True, plus=''):
# cleanup为True则识别完成后删除生成的文本文件
# plus参数为给tesseract的附加高级参数
subprocess.check_output('tesseract ' + img + ' ' +
img + ' ' + plus, shell=True) # 生成同名txt文件
text = ''
with open(img + '.txt', 'r') as f:
text = f.read().strip()
if cleanup:
os.remove(img + '.txt')
return text
# run >>>
# print(image_to_string('./phototest.tif')) # 打印识别出的文本,删除txt文件
# print(image_to_string('./phototest.tif', False)) # 打印识别出的文本,不删除txt文件
# print(image_to_string('./phototest.tif', False, '-l eng')) # 打印识别出的文本,不删除txt文件,同时提供高级参数
# PyTesser废弃...
'''
总结与支持
以上内容为本文的全部介绍,希望能为读者的相关学习提供辅助,同时也欢迎大家继续支持本站获取更多技术资源。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













