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

 更新时间:2020年12月14日 15:59:14   作者:凹凸曼大人  
这篇文章主要介绍了python利用pytesseract 实现本地识别图片文字,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
#!/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):
  '''调整图片大小,对于过大的图片进行压缩
  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):
  while not ts_queue.empty():
    picfile = ts_queue.get()
    filename = path.basename(picfile)
    outfile = 'D:\Study\pythonProject\scrapy\IpProxy\port_zidian.txt'
    img = cv2.imread(picfile, cv2.IMREAD_COLOR)
    print("正在识别图片:\t" + filename)
    message = pytesseract.image_to_string(img,lang = 'eng')
    message = message.replace('', '')
    message = message.replace('\n', '')
    # message = client.basicAccurate(img)  # 通用文字高精度识别,每天 800 次免费
    #print("识别成功!"))
    try:
      filename1 = filename.split('.')[0]
      filename1 = ''.join(filename1)
      with open(outfile, 'a+') as fo:
        fo.writelines('\'' + filename1 + '\'' + ':' + message + ',')
        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\tmp\*"):
      convertimg(picfile, outdir)
    print("图片识别...")
    for picfile in glob.glob("tmp1/*"):
      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 = 'tmp1'
  s = duqu_tupian(t)
  threads = []
  try:
    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))
  except:
    print('识别失败')

实测速度慢,但用了多线程明显提高了速度,但准确度稍低,同样高清图片,90百分识别率。还时不时出现乱码文字,乱空格,这里展现不了,自己实践吧,重点免费的,随便识别,通向100张图片,用时快6分钟了,速度慢了一倍,但是是免费的,挺不错的了。

以上就是python利用pytesseract 实现本地识别图片文字的详细内容,更多关于python 识别图片文字的资料请关注脚本之家其它相关文章!

相关文章

  • Python IndexError报错分析及解决方法

    Python IndexError报错分析及解决方法

    在Python编程中,IndexError是一种常见的异常类型,它通常发生在尝试访问序列(如列表、元组或字符串)中不存在的索引时,本文将深入分析IndexError的成因、表现形式,并提供相应的解决办法,同时附带详细的代码示例,需要的朋友可以参考下
    2024-07-07
  • Python 和 JS 有哪些相同之处

    Python 和 JS 有哪些相同之处

    Python 是一门运用很广泛的语言,自动化脚本、爬虫,甚至在深度学习领域也都有 Python 的身影。下面通过本文给大家介绍Python 和 JS 有哪些相同之处,需要的朋友参考下吧
    2017-11-11
  • Python语法学习之进程的创建与常用方法详解

    Python语法学习之进程的创建与常用方法详解

    本文我们将学习一下在 Python 中去创建并使用多进程的方法,可以通过创建多个进程来帮助我们提高脚本执行的效率,感兴趣的可以了解一下
    2022-04-04
  • Python3中的最大整数和最大浮点数实例

    Python3中的最大整数和最大浮点数实例

    今天小编就为大家分享一篇Python3中的最大整数和最大浮点数实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • 解决python 执行sql语句时所传参数含有单引号的问题

    解决python 执行sql语句时所传参数含有单引号的问题

    这篇文章主要介绍了解决python 执行sql语句时所传参数含有单引号的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • Celery批量异步调用任务一直等待结果问题

    Celery批量异步调用任务一直等待结果问题

    这篇文章主要介绍了Celery批量异步调用任务一直等待结果问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • Python获取excel内容及相关操作代码实例

    Python获取excel内容及相关操作代码实例

    这篇文章主要介绍了Python获取excel内容及相关操作代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • Python实现贪心算法的示例

    Python实现贪心算法的示例

    这篇文章主要介绍了Python实现贪心算法的示例,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-04-04
  • python单向循环链表实例详解

    python单向循环链表实例详解

    这篇文章主要为大家详细介绍了python单向循环链表实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • 使用Python自制一个回收站清理器

    使用Python自制一个回收站清理器

    经常笔记本电脑的回收站存储了很多的文件,需要打开回收站全部选中进行清理。这篇文章将使用Python自制一个回收站清理器,需要的可以参考一下
    2023-03-03

最新评论