首页 > temp > python入门教程 >
-
用python帮别人写了个文字识别程序
前言
就在前几天一个大一学妹打破了我繁忙的生活,我纳闷了,直接问她啥事啊(老直男了)

原来是找我帮个忙,作为好学长那肯定得助人为乐啊…

话不多说,进入正题
一.需求分析
根据学妹的描述来看,就只是想要一个能识别图片文字的程序,那就不管啥排版了,直接依次识别算了,主要是忙…那我直接用百度的ocr就行了,半小时搞定它!
二.代码实现
1.百度文字识别
文字识别官方入口
https://ai.baidu.com/tech/ocr/general

点击立即使用,我们就白嫖吧,反正一个月也用不到1000次

创建应用,输入应用名称,这个随意哈,然后选一个文字识别-免费的,有钱的话当我没说。
下图创建成功。

一会API Key和Secret Key是要使用的。
2.查看文档获取access_token
接下来就要去看看文档了,看是怎么使用的
https://ai.baidu.com/ai-doc/OCR/1k3h7y3db
不会看文档的小伙伴,我直接就讲我需要的东西了,其余的大家自己学着看吧。
从文档来看,我们首先要获取一个东西——access_token
官网代码
# encoding:utf-8 import requests # client_id 为官网获取的AK, client_secret 为官网获取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】' response = requests.get(host) if response: print(response.json()) 我的代码 import requests def access_token(): url = 'https://aip.baidubce.com/oauth/2.0/token' token_ = { 'grant_type': 'client_credentials', # API Key 'client_id': '官网获取的AK', # ecret Key 'client_secret': '官网获取的SK' } res = requests.post(url, data=token_) res = res.json() print(res) access_token = res['access_token'] print(access_token) return access_token if __name__ == '__main__': access_token()
官网说推荐使用post,那我们就用post,但是官方代码是用的get这种方法,其实结果都一样,都能得到需要的数据。只不过官方的代码还需要一步提取出access_token。
access_token = response.json()['access_token']

然后就能得到access_token了。

如果在这个过程中遇到错误,文档也有,而且会比我讲的详细,所以遇到问题的话可以先看文档,实在不行可以问我。
获取access_token的函数
def access_token(): url = 'https://aip.baidubce.com/oauth/2.0/token' token_ = { 'grant_type': 'client_credentials', # API Key 'client_id': '自己获取', # ecret Key 'client_secret': '自己获取' } res = requests.post(url, data=token_) res = res.json() print(res) access_token = res['access_token'] print(access_token) return access_token
当我们需要用时直接调用就行了。

根据文档的说明,我们就开始写读取图片的代码了

3.图片代码
def raed_pic(): url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" request_url = url + "?access_token=" + access_token() f = open('6.jpg', 'rb') img = base64.b64encode(f.read()) # 参数看文档 params = {"image": img, "language_type": "CHN_ENG", "recognize_granularity": "small", } headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(request_url, data=params, headers=headers) # print(response) # res = response.json() # print(res) # 判断是否响应成功 if response: # 保存读出文字的文件,自动创建 file_name = "yiming6.txt" # 这个没说的了,就是写入操作 with open(file_name, 'w', encoding='utf-8') as f: for j in res: f.write(j["words"] + "\n")
4.代码部分解读
从json分析来看我们只要提取当中的words_result里面的words


三.效果展示
效果如下:

nice!当然可以写个循环然后直接遍历一个文件夹里面的所有图片,就可以得到每张图的文字了,再读取里面的文字放在同一个txt文件里面,有闲工夫的小伙伴可以试一试,我就不写了。最后也成功得到学妹的奶茶,就不上图片了,嘻嘻嘻~
原文:https://www.cnblogs.com/pythonQqun200160592/p/15517367.html