python 利用百度API识别图片文字(多线程版)


Posted in Python onDecember 14, 2020
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 09:37:38 2018
利用百度api实现图片文本识别
@author: XnCSD
"""

import glob
from os import path
import os
from aip import AipOcr
from PIL import Image
from queue import Queue
import threading
import datetime

def convertimg(picfile, outdir):
  '''调整图片大小,对于过大的图片进行压缩
  picfile:  图片路径
  outdir:  图片输出路径
  '''
  img = Image.open(picfile)
  width, height = img.size
  while (width * height > 4000000): # 该数值压缩后的图片大约 两百多k
    width = width // 2
    height = height // 2
  new_img = img.resize((width, height), Image.BILINEAR)
  new_img.save(path.join(outdir, os.path.basename(picfile)))


def baiduOCR(ts_queue):
  """利用百度api识别文本,并保存提取的文字
  picfile:  图片文件名
  outfile:  输出文件
  """
  while not ts_queue.empty():
    picfile = ts_queue.get()
    filename = path.basename(picfile)
    outfile = 'D:\Study\pythonProject\scrapy\IpProxy\port_zidian.txt'
    APP_ID = '' # 刚才获取的 ID,下同
    API_KEY = ''
    SECRECT_KEY = ''
    client = AipOcr(APP_ID, API_KEY, SECRECT_KEY)

    i = open(picfile, 'rb')
    img = i.read()
    print("正在识别图片:\t" + filename)
    message = client.basicGeneral(img) # 通用文字识别,每天 50 000 次免费
    # message = client.basicAccurate(img)  # 通用文字高精度识别,每天 800 次免费
    #print("识别成功!")
    i.close()
    try:
      filename1 = filename.split('.')[0]
      filename1 = ''.join(filename1)
      with open(outfile, 'a+') as fo:
        for text in message.get('words_result'):
          fo.writelines('\'' + filename1 + '\'' + ':' + text.get('words') + ',')
          fo.writelines('\n')
        # fo.writelines("+" * 60 + '\n')
        # fo.writelines("识别图片:\t" + filename + "\n" * 2)
        # fo.writelines("文本内容:\n")
        # # 输出文本内容
        # for text in message.get('words_result'):
        #   fo.writelines(text.get('words') + '\n')
        # fo.writelines('\n' * 2)
      os.remove(filename)
      print("识别成功!")
    except:
      print('识别失败')



    print("文本导出成功!")
    print()
def duqu_tupian(dir):
  ts_queue = Queue(10000)

  outdir = dir
  # if path.exists(outfile):
  #   os.remove(outfile)
  if not path.exists(outdir):
    os.mkdir(outdir)
  print("压缩过大的图片...")
  # 首先对过大的图片进行压缩,以提高识别速度,将压缩的图片保存与临时文件夹中
  try:
    for picfile in glob.glob(r"D:\Study\pythonProject\scrapy\IpProxy\端口\*"):
      convertimg(picfile, outdir)
    print("图片识别...")
    for picfile in glob.glob("tmp/*"):
      ts_queue.put(picfile)
      #baiduOCR(picfile, outfile)
      #os.remove(picfile)
    print('图片文本提取结束!文本输出结果位于文件中。' )
    #os.removedirs(outdir)
    return ts_queue
  except:
    print('失败')

if __name__ == "__main__":

  start = datetime.datetime.now().replace(microsecond=0)
  t = 'tmp'
  s = duqu_tupian(t)
  threads = []
  for i in range(100):
    t = threading.Thread(target=baiduOCR, name='th-' + str(i), kwargs={'ts_queue': s})
    threads.append(t)
  for t in threads:
    t.start()
  for t in threads:
    t.join()
  end = datetime.datetime.now().replace(microsecond=0)
  print('删除耗时:' + str(end - start))

速度快,准确率99百分,100里必回出错一张。

实测,识别1500张图片,还是小图片验证码大小,高清,用时30秒,不能识别150张,出错14张左右。  但总体快,不会出现乱码啥的。

python 利用百度API识别图片文字(多线程版)

以上就是python 利用百度API识别图片文字(多线程版)的详细内容,更多关于python 识别图片文字的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python中的默认参数详解
Jun 24 Python
基于Django的python验证码(实例讲解)
Oct 23 Python
今天 平安夜 Python 送你一顶圣诞帽 @微信官方
Dec 25 Python
Python实现的用户登录系统功能示例
Feb 05 Python
Appium Python自动化测试之环境搭建的步骤
Jan 23 Python
Python实现E-Mail收集插件实例教程
Feb 06 Python
Ubuntu18.04下python版本完美切换的解决方法
Jun 14 Python
解决Python3用PIL的ImageFont输出中文乱码的问题
Aug 22 Python
PyTorch的torch.cat用法
Jun 28 Python
python实现画图工具
Aug 27 Python
python selenium 获取接口数据的实现
Dec 07 Python
Pytorch distributed 多卡并行载入模型操作
Jun 05 Python
python3中for循环踩过的坑记录
Dec 14 #Python
Python 数据分析之逐块读取文本的实现
Dec 14 #Python
Python 2.6.6升级到Python2.7.15的详细步骤
Dec 14 #Python
python 通过pip freeze、dowload打离线包及自动安装的过程详解(适用于保密的离线环境
Dec 14 #Python
Pandas中DataFrame交换列顺序的方法实现
Dec 14 #Python
python中time、datetime模块的使用
Dec 14 #Python
全面介绍python中很常用的单元测试框架unitest
Dec 14 #Python
You might like
dedecms中常见问题修改方法总结
2007/03/21 PHP
php 浮点数比较方法详解
2017/05/05 PHP
$()JS小技巧
2007/07/21 Javascript
JSON扫盲帖 JSON.as类教程
2009/02/16 Javascript
在NodeJS中启用ECMAScript 6小结(windos以及Linux)
2014/07/15 NodeJs
js使用for循环及if语句判断多个一样的name
2014/09/09 Javascript
浅析AMD CMD CommonJS规范--javascript模块化加载学习心得总结
2016/03/16 Javascript
Markdown与Bootstrap相结合实现图片自适应属性
2016/05/04 Javascript
基于javascript实现表格的简单操作
2016/05/21 Javascript
mvvm双向绑定机制的原理和实现代码(推荐)
2016/06/07 Javascript
微信小程序 switch组件详解及简单实例
2017/01/10 Javascript
vue.js组件之间传递数据的方法
2017/07/10 Javascript
js实现移动端轮播图
2020/12/21 Javascript
深入理解vue-class-component源码阅读
2019/02/18 Javascript
Node爬取大批量文件的方法示例
2019/06/28 Javascript
jQuery实现form表单基于ajax无刷新提交方法实例代码
2019/11/04 jQuery
微信小程序 wx:for 与 wx:for-items 与 wx:key的正确用法
2020/05/19 Javascript
python使用xlrd实现检索excel中某列含有指定字符串记录的方法
2015/05/09 Python
Python中Continue语句的用法的举例详解
2015/05/14 Python
python避免死锁方法实例分析
2015/06/04 Python
选择Python写网络爬虫的优势和理由
2019/07/07 Python
Django用户认证系统 Web请求中的认证解析
2019/08/02 Python
德国大型的家具商店:Pharao24.de
2016/10/02 全球购物
加拿大花店:1800Flowers.ca
2016/11/16 全球购物
Elemis美国官网:英国的第一豪华护肤品牌
2018/03/15 全球购物
电大本科自我鉴定
2014/02/05 职场文书
2014年入党积极分子党课学习心得体会模板
2014/04/03 职场文书
10的分与合教学反思
2014/04/30 职场文书
公司年底活动方案
2014/08/17 职场文书
行政文员实习自我鉴定范文
2014/09/14 职场文书
2014年采购员工作总结
2014/11/18 职场文书
小平您好观后感
2015/06/09 职场文书
治理商业贿赂工作总结
2015/08/10 职场文书
Python selenium模拟网页点击爬虫交管12123违章数据
2021/05/26 Python
Nginx四层负载均衡的配置指南
2021/06/11 Servers