python实现批量图片文字识别(ocr)

最近有ocr方面的需求,而且是批量的,python能不能干这么件事呢,肯定是可以的,基于百度智能云和python结合,实现了我们的需求,今天分享出来,做个备份

import glob
from os import path
import os
from aip import AipOcr
from PIL import Image

'''使用时只需要修改百度智能云接口,位于baiduOCR函数,和图片存放位置,位于倒数第三行'''

def baiduOCR(outfile):
    """利用百度api识别文本,并保存提取的文字
    picfile:    图片文件名
    outfile:    输出文件
    """
    filename = path.basename(picfile)

    APP_ID = '你的APP_ID'
    API_KEY = '你的API_KEY'
    SECRET_KEY = '你的SECRET_KEY'
    client = AipOcr(APP_ID, API_KEY,SECRET_KEY)

    i = open(picfile, 'rb')
    img = i.read()
    print("正在识别图片:\t" + filename)
    message = client.basicGeneral(img)  # 通用文字识别,每天 50 000 次免费
    # message = client.basicAccurate(img)   # 通用文字高精度识别,每天 500 次免费
    print("识别成功!")
    i.close()

    with open(outfile, 'a+',encoding='utf-8') as fo:
        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)
    print("文本导出成功!")
    print()

if __name__ == "__main__":
    open('result.txt', 'a+',encoding='utf-8').close()
    outfile = 'result.txt'
    for picfile in glob.glob("C:\\Users\\25801路西\\Desktop\\test_image\\*"):
        baiduOCR(outfile)
    print('图片文本提取结束!文本输出结果位于 %s 文件中。' % outfile)

使用时只需要修改百度智能云接口,位于baiduOCR函数,和图片存放位置,位于倒数第三行

获取百度智能云接口的教程有很多,我就不做赘述了,识别效果还是很不错的哦

效果展示

python实现批量(上万张)图片文字识别并写入excel表格

你可能感兴趣的:(python玩出个性,python)