''' 百度AI开放平台,身份证识别应用,此代码用于国徽面,后期完成信息面获取代码及界面设计。 ''' #导入相关库 # encoding:utf-8 import requests import base64 import re #API_Key Secret_Key 请从百度AI开放平台申请。 API_Key = "dz***********2" Secret_Key = "zU**3Mw***Gfd7yK****Z" #调用鉴权接口获取token,方法参考:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu中示例代码 def get_access_token(): url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+ API_Key +"&client_secret="+Secret_Key payload = "" headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) access_token = re.findall(r'access_token":"(.*?)"',response.text) return access_token #识别过程代码,参考:https://ai.baidu.com/ai-doc/OCR/rk3h7xzck中的示例代码 request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard" # 二进制方式打开图片文件,“e:/lai.jpg”为识别的身份证图片的本地地址 f = open('e:/lai.jpg', 'rb') img = base64.b64encode(f.read()) params = {"id_card_side":"front","image":img} #获取access_token access_token = get_access_token() #填入access_token信息 request_url = request_url + "?access_token=" + str(access_token) headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(request_url, data=params, headers=headers) #如果识别结果不为空,打印识别关键信息 if response: #从response.json()中取出识别的信息 sxrq = re.findall(r"'签发日期': {'words': '(.*?)'",str(response.json())) ssrq = re.findall(r"'失效日期': {'words': '(.*?)'",str(response.json())) qfjg = re.findall(r"'签发机关': {'words': '(.*?)'", str(response.json())) #打印信息 print("签发日期:" + str(sxrq)) print("失效日期:"+str(ssrq)) print("签发机关:" + str(qfjg))
识别结果效果如下: