图片图像识别年龄层次

原创
小哥 3年前 (2022-11-16) 阅读数 81 #大杂烩
(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()

阅读方法II 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)

(5)
def 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()

(6)
def 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()

(7)
def 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)

(8)
if __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

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除