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

#!/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 识别图片文字的资料请关注我们其它相关文章!

(0)

相关推荐

  • python3使用Pillow、tesseract-ocr与pytesseract模块的图片识别的方法

    1.安装Pillow pip install Pillow 2.安装tesseract-ocr github地址: https://github.com/tesseract-ocr/tesseract 或本地下载地址:https://www.jb51.net/softs/538925.html windows: The latest installer can be downloaded here: tesseract-ocr-setup-3.05.01.exe and tesseract-oc

  • python opencv pytesseract 验证码识别的实现

    一.环境配置 需要 pillow 和 pytesseract 这两个库,pip install 安装就好了. install pillow -i http://pypi.douban.com/simple --trusted-host pypi.douban.com pip install pytesseract -i http://pypi.douban.com/simple --trusted-host pypi.douban.com 安装好Tesseract-OCR.exe pytesse

  • Python图像处理之图片文字识别功能(OCR)

    OCR与Tesseract介绍 将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR).可以实现OCR 的底层库并不多,目前很多库都是使用共同的几个底层OCR 库,或者是在上面进行定制. Tesseract 是一个OCR 库,目前由Google 赞助(Google 也是一家以OCR 和机器学习技术闻名于世的公司).Tesseract 是目前公认最优秀.最精确的开源OCR 系统. 除 了极高的精确度,Tesseract 也具有很高的灵活性.它可

  • Python3使用腾讯云文字识别(腾讯OCR)提取图片中的文字内容实例详解

    百度OCR体验地址: https://ai.baidu.com/tech/imagerecognition/general 腾讯OCR体验地址: https://cloud.tencent.com/act/event/ocrdemo 测试结果是:腾讯的效果要比百度的好 腾讯云目前额度是: 每个接口 1,000次/月免费,有6个文字识别的接口,一共是6,000次/月 百度接口调用之前写过文章 python实现百度OCR图片识别过程解析 使用步骤 1.注册账号: https://cloud.tenc

  • Python pytesseract验证码识别库用法解析

    环境 centos7 python3 pytesseract只是tesseract-ocr的一种实现接口.所以要先安装tesseract-ocr(大名鼎鼎的开源的OCR识别引擎). 依赖安装 yum install-y automake autoconf libtool gcc gcc-c++ yum install-y libpng-devel libjpeg-devel libtiff-devel giflib-devel 安装依赖的leptonica库 wget http://www.le

  • Python基于内置库pytesseract实现图片验证码识别功能

    这篇文章主要介绍了Python基于内置库pytesseract实现图片验证码识别功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 环境准备: 1.安装Tesseract模块 git文档地址:https://digi.bib.uni-mannheim.de/tesseract/ 下载后就是一个exe安装包,直接右击安装即可,安装完成之后,配置一下环境变量,编辑 系统变量里面 path,添加下面的安装路径: 2.如果您想使用其他语言,请下载相应的

  • 如何利用Python识别图片中的文字

    一.前言 不知道大家有没有遇到过这样的问题,就是在某个软件或者某个网页里面有一篇文章,你非常喜欢,但是不能复制.或者像百度文档一样,只能复制一部分,这个时候我们就会选择截图保存.但是当我们想用到里面的文字时,还是要一个字一个字打出来.那么我们能不能直接识别图片中的文字呢?答案是肯定的. 二.Tesseract 文字识别是ORC的一部分内容,ORC的意思是光学字符识别,通俗讲就是文字识别.Tesseract是一个用于文字识别的工具,我们结合Python使用可以很快的实现文字识别.但是在此之前我们需

  • Python调用百度OCR实现图片文字识别的示例代码

    百度AI提供了一天50000次的免费文字识别额度,可以愉快的免费使用!下面直接上方法: 首先在百度AI创建一个应用,按照下图创建即可,创建后会获得如下: 创建后会获得如下信息: APP_ID = '******' API_KEY = '************' SECRET_KEY = '**************' 下面就是百度API包的安装,在终端cmd输入如下语句直接pip方式安装,注意是 baidu-api 哦! pip install --user baidu-aip 接下来上py

  • python3光学字符识别模块tesserocr与pytesseract的使用详解

    OCR,即Optical Character Recognition,光学字符识别,是指通过扫描字符,然后通过其形状将其翻译成电子文本的过程,对应图形验证码来说,它们都是一些不规则的字符,这些字符是由字符稍加扭曲变换得到的内容,我们可以使用OCR技术来讲其转化为电子文本,然后将结果提取交给服务器,便可以达到自动识别验证码的过程 tesserocr与pytesseract是Python的一个OCR识别库,但其实是对tesseract做的一层Python API封装,pytesseract是Goog

  • python下调用pytesseract识别某网站验证码的实现方法

    一.pytesseract介绍 1.pytesseract说明 pytesseract最新版本0.1.6,网址:https://pypi.python.org/pypi/pytesseract Python-tesseract is a wrapper for google's Tesseract-OCR ( http://code.google.com/p/tesseract-ocr/ ). It is also useful as a stand-alone invocation scrip

  • python利用pytesseract 实现本地识别图片文字

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- import glob from os import path import os import pytesseract from PIL import Image from queue import Queue import threading import datetime import cv2 def convertimg(picfile, outdir): '''调整图片大小,对于过大的图片进行

随机推荐