基于Python的OCR实现示例

所属分类: 脚本专栏 / python 阅读数: 614
收藏 0 赞 0 分享

摘要:

近几天在做一个东西,其中需要对图像中的文字进行识别,看了前辈们的文章,找到两个较简单的方法:使用python的pytesseract库和调用百度AI平台接口。写下这篇文章做一个比较简短的记录和学习,后期如果有新内容再行补充。

1、使用python的pytesseract库

主要是安装库,比较简单,直接使用 pip install 安装即可;另外,如果进行中文识别,需要下载语言包,并配置好相应环境,具体操作可以进行百度,教程有不少。因为这个识别方法比较简单(但效果并不是很理想),下面直接贴出测试代码:

import pytesseract
from PIL import Image
img = Image.open('./testImages/test01.jpg')
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
s = pytesseract.image_to_string(img, lang='chi_sim') #不加lang参数的话,默认进行英文识别
print(s)

2、调用百度AI平台接口(有调用次数限制,通用50000次/天,学习完全够用)

这个类似于调用接口实现词法分析等操作,首先通过注册获得APP_ID、API_KEY、SECRET_KEY,然后调用接口实现OCR。由于是在线API,如果图片体积比较大,涉及到上传数据、分析数据、返回数据等一系列操作,需要一定的时间。此外,因为返回的是 dict 类型数据,所以需要对结果进行处理(这套算法是按行识别文字的,准确率较高,基本可以直接将结果进行提取和拼接)。实现起来比较简单,下面直接贴出代码:

from aip import AipOcr
APP_ID = '00000000'
API_KEY = '00000000000000000000'
SECRET_KEY = '00000000000000000000'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
 
def get_file_content(filePath):
  with open(filePath, 'rb') as fp:
    return fp.read()
 
def image2text(fileName):
  image = get_file_content(fileName)
  dic_result = client.basicGeneral(image)
  res = dic_result['words_result']
  result = ''
  for m in res:
    result = result + str(m['words'])
  return result
 
getresult = image2text('./test01.jpg')
print(getresult)

小结:

主要是初次接触OCR这个领域所做的一些笔记,后续再深入进行学习。

python实现的ocr接口

import pytesseract
import requests
from PIL import Image
from PIL import ImageFilter
from StringIO import StringIO
from werkzeug.utils import secure_filename
from gevent import monkey
from gevent.pywsgi import WSGIServer
monkey.patch_all()
from flask import Flask,render_template,jsonify,request,send_from_directory
import time
import os
import base64
import random


app = Flask(__name__)
UPLOAD_FOLDER='upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['png','jpg','JPG','PNG'])

def allowed_file(filename):
  return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS

@app.route('/',methods=['GET'],strict_slashes=False)
def indexpage():
  return render_template('index.html')

@app.route('/',methods=['POST'],strict_slashes=False)
def api_upload():
  log = open("error.log","w+")
  file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
  if not os.path.exists(file_dir):
    os.makedirs(file_dir)
  print request.headers
  print >> log, request.headers
  f = request.files['file']
  postLang = request.form.get("lang", type=str) 

  log.close()

  if f and allowed_file(f.filename):
    fname = secure_filename(f.filename)
    ext = fname.rsplit('.',1)[1]
    unix_time = int(time.time())
    new_filename = str( random.randrange(0, 10001, 2))+str(unix_time)+'.'+ext
    f.save(os.path.join(file_dir,new_filename))
    if cmp(postLang, "chi_sim"):
      strboxs = pytesseract.image_to_boxes(Image.open("/var/OCRhtml/upload/" + new_filename), lang="chi_sim")
      strdata = pytesseract.image_to_string(Image.open("/var/OCRhtml/upload/" + new_filename), lang="chi_sim")
      print "Chinese"
    else:
      strboxs = pytesseract.image_to_boxes(Image.open("/var/OCRhtml/upload/"+new_filename))
      strdata = pytesseract.image_to_string(Image.open("/var/OCRhtml/upload/"+new_filename))
    return jsonify({"errno":0, "msg":"succeed ","data":strdata,"info":strboxs})
  else:
    return jsonify({"errno":1001, "errmsg":u"failed"})

if __name__ == '__main__':
  http_server = WSGIServer(('', 80), app)
  http_server.serve_forever()
更多精彩内容其他人还在看

pandas的qcut()方法详解

这篇文章主要介绍了pandas的qcut()方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

从列表或字典创建Pandas的DataFrame对象的方法

这篇文章主要介绍了从列表或字典创建Pandas的DataFrame对象的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas.DataFrame的pivot()和unstack()实现行转列

这篇文章主要介绍了pandas.DataFrame的pivot()和unstack()实现行转列,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

pandas中的series数据类型详解

这篇文章主要介绍了pandas中的series数据类型详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas 时间格式转换的实现

这篇文章主要介绍了pandas 时间格式转换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

python中时间、日期、时间戳的转换的实现方法

这篇文章主要介绍了python中时间、日期、时间戳的转换的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas进行时间数据的转换和计算时间差并提取年月日

这篇文章主要介绍了pandas进行时间数据的转换和计算时间差并提取年月日,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法

这篇文章主要介绍了详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

python和c语言的主要区别总结

在本篇文章里小编给各位整理了关于python和c语言的主要区别的相关知识帖内容,有需要的朋友们学习阅读下。
收藏 0 赞 0 分享

选择Python写网络爬虫的优势和理由

在本篇文章里小编给各位整理了一篇关于选择Python写网络爬虫的优势和理由以及相关代码实例,有兴趣的朋友们阅读下吧。
收藏 0 赞 0 分享
查看更多