Python调用百度智能云:文字识别(每天一个python小项目)

使用Python和百度API实现文字识别,
该代码示例展示了一个基于Python的简单文字识别应用,利用百度AipOcrAPI进行图像文字检测和识别。用户可以选择图片文件,程序会读取图片并使用百度API进行文字提取,然后将结果显示在TkinterGUI的文本框中。此外,还提供了清空文本框的功能。
from aip import AipOcr
import requests
from requests.exceptions import RequestException
import tkinter as tk
from PIL import Image, ImageTk
import tkinter.filedialog

def wenzi():
    APP_ID = 'XXX'
    API_KEY = 'XXX'
    SECRET_KEY = 'XXX'

    aip_orc = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    file_path = tk.filedialog.askopenfilename()

    def get_file_content(file_path):
        with open(file_path, 'rb') as f:
            return f.read()

    options = {}
    options['language_type'] = 'true'
    options['detect_direction'] = 'true'
    options['detect_language'] = 'true'
    result = aip_orc.basicAccurate(get_file_content(file_path), options)
    a = ''
    for i in range(len(result['words_result'])):
        a = a + ' ' + result['words_result'][i]['words']
    text.delete(1.0, "end")  # 清空输出文本框
    text.insert('end', a)  # 将翻译结果添加到输出文本框中

#定义清空文本框的函数
def delete():
  text.delete(1.0,"end")  

window = tk.Tk()  #创建window窗口
window.title("文字识别器")  # 定义窗口名称
text = tk.Text(window, height=18) 
text.grid(row=0)

# 添加一个按钮,用于触发识别功能
t_button = tk.Button(window, text='识别', relief=tk.RAISED, width=8, height=1,font='宋体',bg='red',fg='white',command=wenzi)
# 添加一个按钮,用于触发清空输出文本框
button2 = tk.Button(window, text='清空',font='宋体', relief=tk.RAISED,width=8, height=1, command=delete)
#完成界面布局,设置各个控件的位置
t_button.grid(row=0,column=1,padx=2)
button2.grid(row=0,column=3,padx=2)
tk.mainloop()

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值