百度OCR图片识别文本

1、登录百度云,注册OCR帐号:https://console.bce.baidu.com/ai/?_=1607675504636&fromai=1#/ai/ocr/app/list

创建任意应用后,出现如下内容,保存appid,apikey,secret key,这三个内容是后面要用到的参数,保存哦

2、获取token,浏览器中输入下面的内容,client_id值为API Key值,client_secret值为Secret Key值 ,要替换哦!!

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=API Key值&client_secret=Secret Key值

返回内容中,找到access_token值,如下图,将access_token保存,

3、确定要使用的接口,我用的是“通用文字识别(高精度版)”接口

https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic

刚开始用的标准版,发现标准版错误率挺高,又换的高精度版,还是会有错误,必竟是免费的,凑合用吧

官方文档接口介绍,自己查看,我用的python脚本来调用的接口,图片文件名为code.png,根据自己的图片名称修改,修改代码中的access_token值 后,就可以直接使用了,最后将识别出的文字内容放到code.txt文本中,用于下一步登录的调用

import requests
import base64
import urllib
import json
# 图片编码为base64,本地图片为code.png
with open('code.png', 'rb') as fin:
    image_data = fin.read()
    #print(image_data)
    base64_data = base64.b64encode(image_data)
    #print(base64_data)

    fout = open('base64_content.txt', 'w')
    fout.write(base64_data.decode())
    fout.close()
# base64 转码为urlencode    urllib.parse.quote(string, safe='/', encoding=None, errors=None)
file = open('base64_content.txt', 'r').read()
#print('base64编码:'+file)
print ('****************************************************')
ur = urllib.parse.quote(file)   #urlcode编码
#print('urlcode编码:'+ur)
ur2 = urllib.parse.unquote(ur)  #urlcode解码
#print(ur2)

def get_ocr_code():
	#OCR_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'    #通用文字识别(标准版)
	OCR_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic'    #通用文字识别(高精度版)
	image_url1 = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'   #要识别的图片地址
	image_url2 = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'   #要识别的图片地址
	data = {
			'access_token':'输入之前保存的access_token值',
			'language_type':'CHN_ENG',
			'image':file     #base64
			#'url':image_url1     #url和image参加二选一

	}
	response = requests.post(OCR_url,data=data)
	#print(response.text)
	res_text = response.text   #获得的返回数据使用text方法进行获取
	print(res_text)  

	jsonobj = json.loads(res_text)     #将响应内容转换为Json对象
	print (jsonobj)
	log_id = jsonobj['log_id']         #从Json对象获取想要的内容
	words_result = jsonobj['words_result']
	print(words_result)
	print(words_result[0]['words'])   #从数组中获取想要的字段,再做去空格
	code = words_result[0]['words'].replace(" ", "")   #去除全部空格
	
	
	
	print (u'验证码为:'+code)

	#将code值放到txt文档中
	file2 = open('code.txt',mode='w')
	file2.write(code)
	file2.close()
	return code

	
if __name__ == "__main__":
	get_ocr_code()

看下最后返回的内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值