Python卡证识别脚本2.0版本
需要安装requests,pandas库,另外关于token的获取,可以自行到百度智能云官方查看如何获取哦,有视频讲解,很方便的。
import requests
import base64
import pandas as pd
import os
'''
身份证识别
'''
class baidu_auto_id_card_ocr():
def __init__(self):
self.request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
self.access_token = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
self.headers = {'content-type': 'application/x-www-form-urlencoded'}
self.file_path = r"D:/id_card"
def read_img(self):
list = []
for img in os.listdir(self.file_path):
f = open(f"{self.file_path}/{img}","rb")
img = base64.b64encode(f.read())
list.append(img)
return list
def get_response(self):
global list
list = []
for image in self.read_img():
params = {"id_card_side":"front","image":image}
request_url = self.request_url + "?access_token=" + self.access_token
response = requests.post(request_url, data=params, headers=self.headers)
if response:
name = response.json()["words_result"]["姓名"]["words"]
nation = response.json()["words_result"]["民族"]["words"]
address = response.json()["words_result"]["住址"]["words"]
number = response.json()["words_result"]["公民身份号码"]["words"]
birth = response.json()["words_result"]["出生"]["words"]
list.append([name,nation,address,number,birth])
print(list)
return list
def write_to_excel(self):
df = pd.DataFrame(self.get_response(),columns=["姓名","民族","地址","身份证号","出生年月"])
df.to_excel(r'D:/id_card/识别结果.xlsx',index=False)
return df
if __name__ == '__main__':
id_card = baidu_auto_id_card_ocr()
id_card.read_img()
id_card.write_to_excel()
以上,如有问题,可随时沟通哦~