使用百度云获取身份证信息,python源代码

查看 72|回复 5
作者:oenrjtt   
第一次发帖,不知道 是不是合规,未编译直接发代码,能用到的自行修改
若有违规,请版主第一时间删帖
以下代码适合于在文件夹中多个文件批量提取身份证信息
[Python] 纯文本查看 复制代码from aip import AipOcr
import os
import imghdr
import sys
#import filetype
#代{过}{滤}理服务器访问设置设置
#os.environ["http_proxy"] = "http://localhost:8888"
#os.environ["https_proxy"] = "http://localhost:8888"
#百度云账号,自己填写上自己的百度云开发帐号信息
APP_ID='99999999'
API_KEY='xxxxxxxxxxxxxxxxxxxxx'
SECRET_KEY='xxxxxxxxxxxxxxxxxxxxxx'
#调用百度云接口
client=AipOcr(APP_ID,API_KEY,SECRET_KEY)
def get_file_content(filePath):
    with open(filePath,'rb') as fp:
            return fp.read()
def duqusfzxx(imagefile):
    image=get_file_content(imagefile)
    #识别身份证正面
    idCardSide="front"
    #识别身份证背面
    #idCardSide="back"
    client.idcard(image,idCardSide)
    options={}
    options["detect_direction"]="true" #是否检测图像朝向,默认不检测
    options["detect_risk"]="false"  #是否开启身份证风险类型(身份证复印件)
    #带参数调用身份证识别
    result=client.idcard(image,idCardSide,options)
    #识别为一个list
    #    {'姓名': {'words': '奥巴马', 'location': {'top': 52, 'left': 61, 'width': 34, 'height': 17}}, '民族': {'words': '哈尼', 'location': {'top': 69, 'left': 137, 'width': 9, 'height': 14}}, '住址': {'words': '盛顿特区宜宾法尼亚大道1600号白官', 'location': {'top': 113, 'left': 70, 'width': 118, 'height': 49}}, '公民身份号码': {'words': '', 'location': {'top': 0, 'left': 0, 'width': 0, 'height': 0}}, '出生': {'words': '19610804', 'location': {'top': 90, 'left': 68, 'width': 101, 'height': 26}}, '性别': {'words': '男', 'location': {'top': 78, 'left': 65, 'width': 14, 'height': 15}}}
    id_msg=''
    if isinstance(result,dict):
        words=result['words_result']
        #print(words)
        
        #身份证用下面的两个
        #id_msg=words[u'姓名']['words']+'\t'+words[u'公民身份号码']['words']
        id_msg=words[u'姓名']['words']+'\t'+words[u'公民身份号码']['words']+'\t'+words[u'住址']['words']
        
        print(id_msg)
        #print(words[u'姓名']['words'])
        #print(words[u'公民身份号码']['words'])
        
        #以上内容 建议使用 姓名\t身份证号码方式显示
def bianli(rootDir):
    imgType_list={'jpg','bmp','png','jpeg','jfif'}
    for root,dirs,files in os.walk(rootDir):
        for file in files:
            filepath=os.path.join(root,file)
            #print(imghdr.what(file))
            #print(filetype.guess(filepath))                  
            try:
                #print(filetype.guess(filepath).mime)
                #f(imghdr.what(filepath) in imgType_list):
                f=filepath.rfind(('.'))
                if filepath[f+1:] in imgType_list:
                    duqusfzxx(filepath)               
            except:
                print(filepath+"\t 出错!")
#直接调用,修改一下文件夹即可,也可以写成参数格式,懒得修改了
bianli(r'D:\05.身份验证')
sfz照片正面图片(如图1)
在相应文件夹中运行代码,可以获取姓名、性别、家庭住址、身份证号码等信息(如图2)


图片1.jpg (7.67 KB, 下载次数: 0)
下载附件
2023-3-22 08:23 上传



图片2.jpg (25.98 KB, 下载次数: 0)
下载附件
2023-3-22 08:23 上传

身份证, 姓名

oenrjtt
OP
  

本人纯小白,代码写的挺垃圾的,各位大神见笑了
binstc   

前排学习
89684828   

标记一下,谢谢楼主!
jjoobb123   

谢谢分享,多多学习。
blindcat   

学习了,感谢分享
您需要登录后才可以回帖 登录 | 立即注册

返回顶部