OCR图片识别

import sys
import os
import glob
from os import path
from aip import AipOcr
from PIL import Image
from tkinter  import *
import tkinter.filedialog
root = Tk() #创建主窗口
root.title("功能选择") #设置窗口标题
root.geometry("400x120")

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

    APP_ID ="18640801"  # 刚才获取的 ID,下同
    API_KEY = "SUCoWqGniSB3Ng5uoHzDvn6h"
    SECRECT_KEY = "CRh6EoG4SpGTWQboVKFSA4FIzlFI45KD"
    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();
    
    with open(outfile, 'a+') 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()

def pic():
    picfile = tkinter.filedialog.askopenfilename(initialdir='C',title='选择图片',filetypes=(("所有图片",("*.jpg","*.jpeg","*.png")),('All file','*.*')))

    if picfile != '':
        lb.config(text = "开始文字识别处理...");


        outfile = 'result.txt'
        if path.exists(outfile):
            os.remove(outfile)

        lb.config(text = "图片识别...");
        baiduOCR(picfile, outfile)
        lb.config(text = "图片文本提取结束!文本输出结果位于"+outfile+"文件中");
        
    else:
        lb.config(text = "您未选择文件!");

lb = Label(root,text = '')
lb.pack()
btn1 = Button(root,text='图片识别文字提取',command = pic)
btn1.pack()
lb1 = Label(root,text = '')
lb1.pack()

root.mainloop()

 

上一篇:快递手机号识别


下一篇:pytesseract败北?轻量级muggleOCR问世,同时支持印刷字和验证码识别