图片人脸识别年龄和性别

1# coding=utf-8
import sys
import json
import base64

下面判断是py2还是py3

2# make it work in both python2 both python3
#Python中版本获取Python版本号,在代码中可以通过sys.version, 或者sys.version_info 得到
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib.error import URLError
    from urllib.parse import urlencode
    from urllib.parse import quote_plus
else:
    import urllib2
    from urllib import quote_plus
    from urllib2 import urlopen
    from urllib2 import Request
    from urllib2 import URLError
    from urllib import urlencode

1、

#Python中版本获取Python版本号,在代码中可以通过sys.version_info 得到
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)
>>> sys.version_info.major
3

2、

#Python中版本获取Python版本号,在代码中可以通过sys.version得到
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import sys
>>> sys.version
'3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]'
>>> sys.version[0]
'3'

在浏览器中访问该网站时会弹出证书不受信任,但是忽略仍可继续访问 ,但当使用Python登录时就会抛出_ssl.c:645错误,不能读取页面。
只要忽略就行啦
python 绕过ssl验证的方法

1、导入ssl库

3# skip https auth
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

2、如果使用requests库,可以添加参数 verify=False

requests.get(url=url,headers=headers,verify=False)

需要注意的是这个方法会有屏蔽警告,忽略它

from requests.packages import urllib3
# verify参数控制是否检查证书(默认是ture),通过设置忽略屏蔽警告
urllib3.disable_warnings()
4)
API_KEY = '官网获得替换'
SECRET_KEY = '官网获得替换'
FACE_DETECT = "https://aip.baidubce.com/rest/2.0/face/v3/detect"     #官网的请求URL		
"""  TOKEN start """
TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'

获取Access Token
请求URL数据格式
向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

  • grant_type: 必须参数,固定为client_credentials;
  • client_id: 必须参数,应用的API Key;
  • client_secret: 必须参数,应用的Secret Key;

urlencode()

  • 传入参数类型:字典
  • 功能:将存入的字典参数编码为URL查询字符串,即转换成以key1=value1&key2=value2的形式
  • 导入:from urllib.parse import urlencode

python文件对象提供了三个“读”方法: read()、readline() 和 readlines()。每种方法可以接受一个变量以限制每次读取的数据量。

  • read()
    每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。如果文件大于可用内存,为了保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。

  • readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines()自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for … in … 结构进行处理。

  • readline() 每次只读取一行,通常比readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用readline()。

读取方法一 f=open()

由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用try … finally来实现:

try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()

读取方法二 with open () as f

但是每次都这么写实在太繁琐,所以,Python引入了with语句来自动帮我们调用close()方法:

with open('/path/to/file', 'r') as f:
    print(f.read())

URLError是urllib库的error模块,属性reason表示错误原因

from urllib import request,error
try:
    response = request.urlopen('https://cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)
5def fetch_token():
    params = {'grant_type': 'client_credentials',
              'client_id': API_KEY,
              'client_secret': SECRET_KEY}
    post_data = urlencode(params)#需要提前导入:from urllib.parse import urlencode,#data参数如果要传必须传bytes(字节流)类型的,如果是一个字典,先用urllib.parse.urlencode()编码。
    if (IS_PY3):
        post_data = post_data.encode('utf-8')#返回编码后的字符串
    req = Request(url=TOKEN_URL, data=post_data) 
    try:       
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print(err)
    if (IS_PY3):
        result_str = result_str.decode()
    result = json.loads(result_str)##将信息转换成字典类型,便于查找令牌
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'brain_all_scope' in result['scope'].split(' '):
            print ('please ensure has check the  ability')
            exit()
        return result['access_token']
    else:
        print ('please overwrite the correct API_KEY and SECRET_KEY')
        exit()
6def read_file(image_path):
    f = None
    try:
        f = open(image_path, 'rb')
        return f.read()
    except:
        print('read image file fail')
        return None
    finally:
        if f:
            f.close()
7def request(url, data):
    req = Request(url, data.encode('utf-8'))
    has_error = False
    try:
        f = urlopen(req)
        result_str = f.read()
        if (IS_PY3):
            result_str = result_str.decode()
        return result_str
    except  URLError as err:
        print(err)
8if __name__ == '__main__':
    # get access token
    token = fetch_token()
    # concat url
    url = FACE_DETECT + "?access_token=" + token
    file_content = read_file('MYXJ_20191231193300201_fast.jpg')#图片名称自己更改,图片和代码需要放在一个文件夹
    response = request(url, urlencode(
    {
        'image': base64.b64encode(file_content),
        'image_type': 'BASE64',
        'face_field': 'gender,age',
        'max_face_num': 10
    }))
    data = json.loads(response)
    num = 65;
    if data["error_code"] == 0:
        face_num = data["result"]["face_num"]
        if face_num == 0:
            # could not find face
            print("no face in the picture")
        else:
            # get face list
            face_list = data["result"]["face_list"]
            for face in face_list:
                # male face
                if face["gender"]["type"] == "male":
                    gender = "男"
                # female face
                if face["gender"]["type"] == "female":
                    gender = "女"
                print("顾客" + chr(num))
                print("   性别: " + gender + " 年龄: " + str(face["age"]))
                num = num + 1
    else:
        # print error response
        print(response)

代码来源于:https://ai.baidu.com/ai-doc/FACE/8k3gwxdg8

猜你喜欢

转载自blog.csdn.net/ingenuou_/article/details/104303896