1 Star 0 Fork 0

陈珂715 / API_homework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

API_HOMEWORK_01

Azure

  1. 面部检测+人脸集合相似度
# A-1 面部检测
import requests
import json

# set to your own subscription key value
subscription_key = "61e5f95dc8b54eb9ba68b867ff8da52b"
assert subscription_key

# replace <My Endpoint String> with the string from your endpoint URL
face_api_url = 'https://colleen.cognitiveservices.azure.com/face/v1.0/detect'

# 请求正文body
image_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603539706074&di=6370d0023c82a5155bc3e19af53c55f1&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181024%2F7aeffe6c8e2341358eb3ac9917765ffc.jpeg'

headers = {'Ocp-Apim-Subscription-Key': subscription_key}

# 请求参数parameters
params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    # 可选参数,请仔细阅读API文档
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
}

response = requests.post(face_api_url, params=params,headers=headers, json={"url": image_url})
# json.dumps 将json--->bytes
json.dumps(response.json())
'[{"faceId": "569cd6fa-1d46-43c9-83bd-f4d74639e963", "faceRectangle": {"top": 151, "left": 223, "width": 285, "height": 285}, "faceAttributes": {"smile": 0.0, "headPose": {"pitch": -0.5, "roll": -0.6, "yaw": -0.3}, "gender": "male", "age": 20.0, "facialHair": {"moustache": 0.1, "beard": 0.1, "sideburns": 0.1}, "glasses": "NoGlasses", "emotion": {"anger": 0.0, "contempt": 0.0, "disgust": 0.0, "fear": 0.0, "happiness": 0.0, "neutral": 1.0, "sadness": 0.0, "surprise": 0.0}, "blur": {"blurLevel": "low", "value": 0.0}, "exposure": {"exposureLevel": "goodExposure", "value": 0.53}, "noise": {"noiseLevel": "low", "value": 0.08}, "makeup": {"eyeMakeup": true, "lipMakeup": true}, "accessories": [], "occlusion": {"foreheadOccluded": false, "eyeOccluded": false, "mouthOccluded": false}, "hair": {"bald": 0.04, "invisible": false, "hairColor": [{"color": "black", "confidence": 1.0}, {"color": "other", "confidence": 0.71}, {"color": "gray", "confidence": 0.61}, {"color": "brown", "confidence": 0.34}, {"color": "blond", "confidence": 0.01}, {"color": "red", "confidence": 0.01}, {"color": "white", "confidence": 0.0}]}}}]'
results = response.json()
results
'[{"faceId": "569cd6fa-1d46-43c9-83bd-f4d74639e963", "faceRectangle": {"top": 151, "left": 223, "width": 285, "height": 285}, "faceAttributes": {"smile": 0.0, "headPose": {"pitch": -0.5, "roll": -0.6, "yaw": -0.3}, "gender": "male", "age": 20.0, "facialHair": {"moustache": 0.1, "beard": 0.1, "sideburns": 0.1}, "glasses": "NoGlasses", "emotion": {"anger": 0.0, "contempt": 0.0, "disgust": 0.0, "fear": 0.0, "happiness": 0.0, "neutral": 1.0, "sadness": 0.0, "surprise": 0.0}, "blur": {"blurLevel": "low", "value": 0.0}, "exposure": {"exposureLevel": "goodExposure", "value": 0.53}, "noise": {"noiseLevel": "low", "value": 0.08}, "makeup": {"eyeMakeup": true, "lipMakeup": true}, "accessories": [], "occlusion": {"foreheadOccluded": false, "eyeOccluded": false, "mouthOccluded": false}, "hair": {"bald": 0.04, "invisible": false, "hairColor": [{"color": "black", "confidence": 1.0}, {"color": "other", "confidence": 0.71}, {"color": "gray", "confidence": 0.61}, {"color": "brown", "confidence": 0.34}, {"color": "blond", "confidence": 0.01}, {"color": "red", "confidence": 0.01}, {"color": "white", "confidence": 0.0}]}}}]'
# pandas数据清洗
import pandas as pd
df_face = pd.json_normalize(results)
faceID = df_face['faceId'].values.tolist()
faceID 
df_face.columns
Index(['faceId', 'faceRectangle.top', 'faceRectangle.left',
       'faceRectangle.width', 'faceRectangle.height', 'faceAttributes.smile',
       'faceAttributes.headPose.pitch', 'faceAttributes.headPose.roll',
       'faceAttributes.headPose.yaw', 'faceAttributes.gender',
       'faceAttributes.age', 'faceAttributes.facialHair.moustache',
       'faceAttributes.facialHair.beard',
       'faceAttributes.facialHair.sideburns', 'faceAttributes.glasses',
       'faceAttributes.emotion.anger', 'faceAttributes.emotion.contempt',
       'faceAttributes.emotion.disgust', 'faceAttributes.emotion.fear',
       'faceAttributes.emotion.happiness', 'faceAttributes.emotion.neutral',
       'faceAttributes.emotion.sadness', 'faceAttributes.emotion.surprise',
       'faceAttributes.blur.blurLevel', 'faceAttributes.blur.value',
       'faceAttributes.exposure.exposureLevel',
       'faceAttributes.exposure.value', 'faceAttributes.noise.noiseLevel',
       'faceAttributes.noise.value', 'faceAttributes.makeup.eyeMakeup',
       'faceAttributes.makeup.lipMakeup', 'faceAttributes.accessories',
       'faceAttributes.occlusion.foreheadOccluded',
       'faceAttributes.occlusion.eyeOccluded',
       'faceAttributes.occlusion.mouthOccluded', 'faceAttributes.hair.bald',
       'faceAttributes.hair.invisible', 'faceAttributes.hair.hairColor'],
      dtype='object')

输入图片说明

# A-2 人脸集合相似度对比
import requests
# 1、create  列表
# faceListId
faceListId = "chenke0715" #学生填写
#create_facelists_url = 'https://colleen.cognitiveservices.azure.com/face/v1.0/facelists/{}' #学生填写
create_facelists_url = 'https://colleen.cognitiveservices.azure.com/face/v1.0/facelists/{}'
subscription_key = '61e5f95dc8b54eb9ba68b867ff8da52b'#学生填写
assert subscription_key

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
data = {
        "name": "colleen_photo",
        "userData": "照片库",
        "recognitionModel": "recognition_03",
# 学生填写
    
}

r_create = requests.put(create_facelists_url.format(faceListId),headers=headers,json=data) #学生填写
r_create.content
b''
#先加一张脸试试
# 2、Add face
add_face_url = "https://colleen.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedFaces"#学生填写

assert subscription_key
headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}
img_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603539706074&di=6370d0023c82a5155bc3e19af53c55f1&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181024%2F7aeffe6c8e2341358eb3ac9917765ffc.jpeg" #学生填写

params_add_face={
    "userData":"易烊千玺"
#学生填写
}

r_add_face = requests.post(add_face_url.format(faceListId),headers=headers,params=params_add_face,json={"url":img_url})#学生填写
r_add_face.status_code
200
r_add_face.json()#返回persistedFaceId
{'persistedFaceId': '4a81ae93-c7e0-44df-8fd9-b4e91b53fe03'}
# 封装成函数方便添加图片
def AddFace(img_url=str,userData=str):
    add_face_url ="https://colleen.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedFaces"
    assert subscription_key
    headers = {
        # Request headers
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': subscription_key,
    }
    img_url = img_url

    params_add_face={
        "userData":userData
    }
    r_add_face = requests.post(add_face_url.format(faceListId),headers=headers,params=params_add_face,json={"url":img_url})
    return r_add_face.status_code#返回出状态码
AddFace("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603540349335&di=35250ba9b98bcea1bdc2aaf0685f7bc3&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn10%2F775%2Fw353h422%2F20180627%2Fca15-hencxtu9699461.jpg","易烊昱华")
AddFace("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=673053576,3253296480&fm=26&gp=0.jpg","妈妈")
AddFace("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603539706074&di=6370d0023c82a5155bc3e19af53c55f1&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181024%2F7aeffe6c8e2341358eb3ac9917765ffc.jpeg","易烊千玺")
200
# Get facelist(获取人脸列表)
get_facelist_url ="https://colleen.cognitiveservices.azure.com/face/v1.0/facelists/{}"#学生填写
r_get_facelist = requests.get(get_facelist_url.format(faceListId),headers=headers,params=data)#学生填写
r_get_facelist.json()
{'persistedFaces': [{'persistedFaceId': '4a81ae93-c7e0-44df-8fd9-b4e91b53fe03',
   'userData': '易烊千玺'},
  {'persistedFaceId': '24a39da5-8d4a-4e42-9973-e780c71e70e2',
   'userData': '易烊昱华'},
  {'persistedFaceId': 'cee56ad0-4aa9-4b7f-bb73-b8d665b51c28',
   'userData': '妈妈'},
  {'persistedFaceId': '262ecd78-ec15-4351-88f9-c9fc776a642e',
   'userData': '易烊千玺'}],
 'faceListId': 'chenke0715',
 'name': 'colleen_photo',
 'userData': '照片库'}
faceID =  r_get_facelist.json()['persistedFaces']
faceID
[{'persistedFaceId': '4a81ae93-c7e0-44df-8fd9-b4e91b53fe03',
  'userData': '易烊千玺'},
 {'persistedFaceId': '24a39da5-8d4a-4e42-9973-e780c71e70e2',
  'userData': '易烊昱华'},
 {'persistedFaceId': 'cee56ad0-4aa9-4b7f-bb73-b8d665b51c28', 'userData': '妈妈'},
 {'persistedFaceId': '262ecd78-ec15-4351-88f9-c9fc776a642e',
  'userData': '易烊千玺'}]
# 3、检测人脸的id
# replace <My Endpoint String> with the string from your endpoint URL
face_api_url = 'https://colleen.cognitiveservices.azure.com/face/v1.0/detect'

# 请求正文
image_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603539706074&di=6370d0023c82a5155bc3e19af53c55f1&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181024%2F7aeffe6c8e2341358eb3ac9917765ffc.jpeg'

headers = {'Ocp-Apim-Subscription-Key': subscription_key}

# 请求参数
params = {
   'returnFaceId': 'true',
   'returnFaceLandmarks': 'false',
   # 选择model
   'recognitionModel':'recognition_03',#此参数需与facelist参数一致
   'detectionModel':'detection_01',
   # 可选参数,请仔细阅读API文档
   'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
}

response = requests.post(face_api_url, params=params,
                        headers=headers, json={"url": image_url})
# json.dumps 将json--->字符串
response.json()  
[{'faceId': 'f16bd7d9-eeda-4e0b-91b8-0775b4133ef8',
  'faceRectangle': {'top': 151, 'left': 223, 'width': 285, 'height': 285},
  'faceAttributes': {'smile': 0.0,
   'headPose': {'pitch': -0.5, 'roll': -0.6, 'yaw': -0.3},
   'gender': 'male',
   'age': 20.0,
   'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1},
   'glasses': 'NoGlasses',
   'emotion': {'anger': 0.0,
    'contempt': 0.0,
    'disgust': 0.0,
    'fear': 0.0,
    'happiness': 0.0,
    'neutral': 1.0,
    'sadness': 0.0,
    'surprise': 0.0},
   'blur': {'blurLevel': 'low', 'value': 0.0},
   'exposure': {'exposureLevel': 'goodExposure', 'value': 0.53},
   'noise': {'noiseLevel': 'low', 'value': 0.08},
   'makeup': {'eyeMakeup': True, 'lipMakeup': True},
   'accessories': [],
   'occlusion': {'foreheadOccluded': False,
    'eyeOccluded': False,
    'mouthOccluded': False},
   'hair': {'bald': 0.04,
    'invisible': False,
    'hairColor': [{'color': 'black', 'confidence': 1.0},
     {'color': 'other', 'confidence': 0.71},
     {'color': 'gray', 'confidence': 0.61},
     {'color': 'brown', 'confidence': 0.34},
     {'color': 'blond', 'confidence': 0.01},
     {'color': 'red', 'confidence': 0.01},
     {'color': 'white', 'confidence': 0.0}]}}}]
findsimilars_url = "https://colleen.cognitiveservices.azure.com/face/v1.0/findsimilars"

# 请求正文 faceId需要先检测一张照片获取
data_findsimilars = {
    "faceId":"f16bd7d9-eeda-4e0b-91b8-0775b4133ef8",#取上方的faceID
    "faceListId": "chenke0715",
    "maxNumOfCandidatesReturned": 10,
    "mode": "matchFace"#matchPerson #一种为验证模式,一种为相似值模式
    }

r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)
r_findsimilars.json()
[{'persistedFaceId': '4a81ae93-c7e0-44df-8fd9-b4e91b53fe03',
  'confidence': 1.0},
 {'persistedFaceId': '262ecd78-ec15-4351-88f9-c9fc776a642e',
  'confidence': 1.0},
 {'persistedFaceId': '24a39da5-8d4a-4e42-9973-e780c71e70e2',
  'confidence': 0.20937},
 {'persistedFaceId': 'cee56ad0-4aa9-4b7f-bb73-b8d665b51c28',
  'confidence': 0.09858}]

Face++

  • 参考文档Face++_API
  • 面部检测+人脸集合相似度
  1. 面部检测
# 1、先导入为们需要的模块
import requests

# 2、输入我们API_Key/API_secret
api_key = 'yIk5cY6rxMTY7oMwOlXfQTZqS2gFdfMA'

api_secret = 'o-kNJG-jnqzrheW1IgjN1nRKcHkLprCN'



# 3、目标url
BASE_URL = 'https://api-cn.faceplusplus.com/facepp/v3/detect'  # 请求URL 即平台
img_url1 = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603541371899&di=ecbae5c9e1c7d077b0a3e9c8b673f3c4&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181024%2F7aeffe6c8e2341358eb3ac9917765ffc.jpeg'
# 4、头部headers

headers = {
    'Content-Type': 'application/json',
}

# 5、调用参数

payload = {
    "image_url":img_url1,
    'api_key': api_key,
    'api_secret': api_secret,
    'return_attributes':'gender,age,smiling,emotion', 
}

#  6、requests发送我们请求
r = requests.post(BASE_URL, params=payload, headers=headers)

r.status_code
200
r.content
b'{"request_id":"1603533242,ebe7d391-d1cb-48da-a999-02fff110e16c","time_used":204,"faces":[{"face_token":"17306dd2998d7149c32e440413c395f2","face_rectangle":{"top":178,"left":224,"width":275,"height":275},"attributes":{"gender":{"value":"Male"},"age":{"value":21},"smile":{"value":0.000,"threshold":50.000},"emotion":{"anger":0.003,"disgust":0.003,"fear":0.003,"happiness":0.003,"neutral":95.538,"sadness":4.418,"surprise":0.031}}}],"image_id":"anDVqeiivazHcrLFFvqdAg==","face_num":1}\n'
  1. 人脸集合相似度
#准备工作
api_secret = 'o-kNJG-jnqzrheW1IgjN1nRKcHkLprCN'
api_key =  'yIk5cY6rxMTY7oMwOlXfQTZqS2gFdfMA'  # Replace with a valid Subscription Key here.
#FaceSet Create(创建人脸集合)
import requests,json

display_name = "易烊千玺一家"
outer_id = "0715"
user_data = "3人,妈妈,易烊千玺,弟弟,"
#FaceSet GetDetail(获取人脸集合信息)
CreateFace_Url = "https://api-cn.faceplusplus.com/facepp/v3/detect"
payload = {
    'api_key': api_key,
    'api_secret': api_secret,
    'display_name':display_name,
    'outer_id':outer_id,
    'user_data':user_data
}
# r = requests.post(CreateFace_Url, params=payload)
# r.json()
#FaceSet AddFace(增加人脸信息)
{'faceset_token': '17306dd2998d7149c32e440413c395f2',
 'time_used': 204,
 'face_count': 0,
 'face_added': 0,
 'request_id': '1603533242,ebe7d391-d1cb-48da-a999-02fff110e16c',
 'outer_id': '0715',
 'failure_detail': []}
{'faceset_token': '17306dd2998d7149c32e440413c395f2',
'time_used': 204,
'face_count': 0,
'face_added': 0,
'request_id': '1603533242,ebe7d391-d1cb-48da-a999-02fff110e16c',
'outer_id': '0715',
'failure_detail': []}
GetDetail_Url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail"

payload = {
   'api_key': api_key,
   'api_secret': api_secret,
   'outer_id':outer_id,
}
r = requests.post(GetDetail_Url,params=payload)
r.json()
{'faceset_token': '17306dd2998d7149c32e440413c395f2',
'tags': '',
'time_used': 84,
'user_data': '3人,妈妈,易烊千玺,弟弟,',
'display_name': '易烊千玺一家',
'face_tokens': [],
'face_count': 0,
'request_id': '1603533242,ebe7d391-d1cb-48da-a999-02fff110e16c',
'outer_id': '0715'}
{'faceset_token': '17306dd2998d7149c32e440413c395f2',
'tags': '',
'time_used': 84,
'user_data': '3人,妈妈,易烊千玺,弟弟,',
'display_name': '易烊千玺一家',
'face_tokens': [],
'face_count': 0,
'request_id': '1603533242,ebe7d391-d1cb-48da-a999-02fff110e16c',
'outer_id': '0715'}
AddFace_url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface"

payload = {
   'api_key': api_key,
   'api_secret': api_secret,
   'faceset_token':'17306dd2998d7149c32e440413c395f2',
   'face_tokens':'b0407b9e803ebd39d511cd7956fd5bf5',
}
r = requests.post(AddFace_url,params=payload)
r.json()
   {'faceset_token': '17306dd2998d7149c32e440413c395f2',
 'time_used': 66,
 'face_count': 0,
 'face_added': 0,
 'request_id': '1603547320,97b2f6ef-cf1f-4d66-a6f3-2c237080463d',
 'outer_id': '0715',
 'failure_detail': [{'reason': 'INVALID_FACE_TOKEN',
   'face_token': 'b0407b9e803ebd39d511cd7956fd5bf5'}]}
#FaceSet RemoveFace(移除人脸信息)
   RemoveFace_url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/removeface"

payload = {
    'api_key': api_key,
    'api_secret': api_secret,
    'faceset_token':'17306dd2998d7149c32e440413c395f2',
    'face_tokens':'b0407b9e803ebd39d511cd7956fd5bf5',
}
r = requests.post(RemoveFace_url,params=payload)
r.json()
{'time_used': 86,
 'error_message': 'INVALID_FACESET_TOKEN',
 'request_id': '1603547440,5af5e9ee-cd2a-4ce0-9d19-db705f6ac0d9'}

#FaceSet Update(更新人脸集合信息)

Update_url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/update"

payload = {
   'api_key': api_key,
   'api_secret': api_secret,
   'faceset_token':'17306dd2998d7149c32e440413c395f2',
   'user_data':"3人,妈妈,易烊千玺,弟弟,",
}
r = requests.post(Update_url,params=payload)
r.json()
{'time_used': 66,
 'error_message': 'INVALID_FACESET_TOKEN',
 'request_id': '1603547529,d8dc06c4-62e7-459f-8320-1957f8e33d94'}
#Compare Face(对比人脸相似度) 
yyqx = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603541371899&di=ecbae5c9e1c7d077b0a3e9c8b673f3c4&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181024%2F7aeffe6c8e2341358eb3ac9917765ffc.jpeg"
yyyh = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603557671428&di=aea547af6588bb91b9ab2a1d973e8490&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn10%2F775%2Fw353h422%2F20180627%2Fca15-hencxtu9699461.jpg"
mama = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=673053576,3253296480&fm=26&gp=0.jpg"
# 直接对比
Compare_url = "https://api-cn.faceplusplus.com/facepp/v3/compare"

payload ={
   'api_key': api_key,
   'api_secret': api_secret,
   'image_url1':yyqx,
   'image_url2':yyyh,
   'image_url3':mama,
   
}
r = requests.post(Compare_url,params=payload)
r.json()
{'faces1': [{'face_rectangle': {'width': 275,
    'top': 178,
    'left': 224,
    'height': 275},
   'face_token': '8dfa696349e12172df68f014320bdf8d'}],
 'faces2': [{'face_rectangle': {'width': 50,
    'top': 46,
    'left': 131,
    'height': 50},
   'face_token': '5440c2a6eb03fd7b17bb0a4764737417'}],
 'time_used': 742,
 'thresholds': {'1e-3': 62.327, '1e-5': 73.975, '1e-4': 69.101},
 'confidence': 38.342,
 'image_id2': 'K8IwaYKIHc2dfYUAlrDE5Q==',
 'image_id1': 'anDVqeiivazHcrLFFvqdAg==',
 'request_id': '1603547703,aa5200d8-c9f3-4e5e-91e0-2547093a3866'}

百度API

  1. 面部检测
import requests 

# client_id 为官网获取的APIKey,client_secret为官网获取的Secret Key

host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'
client_id = "CV5V4MkfYzN4jteGhGNkSgZd"
client_secret = "3HOo6KOpWYP5hxGm1H9GwcXU7RsDUtVd"
response = requests.get(host.format(client_id, client_secret))
if response:
    print(response.json())  
    #返回结果{'refresh_token': '25.80a0392336c9e413d5a37f3ae9247c39.315360000.1918916254.282335-22868444', 'expires_in': 2592000, 'session_key': '9mzdDZXovGHVhd1qQrueEoohwSh+DUpGqCx8xy7brN0ECOA79llauAaCro9YoKW0k9p2KHv3hhlcN8ryYM8ct5Y1wk/xeg==', 'access_token': '24.6c3d9de70716e52db9b4701a055f8fa9.2592000.1606148254.282335-22868444', 'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT vis-faceverify_face_feature_sdk wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component', 'session_secret': '8be57abbb2a02afb9455952481be45fc'}
# (排列整齐)
results = response.json()
results
#返回结果{'refresh_token': '25.80a0392336c9e413d5a37f3ae9247c39.315360000.1918916254.282335-22868444',
 'expires_in': 2592000,
 'session_key': '9mzdDZXovGHVhd1qQrueEoohwSh+DUpGqCx8xy7brN0ECOA79llauAaCro9YoKW0k9p2KHv3hhlcN8ryYM8ct5Y1wk/xeg==',
 'access_token': '24.6c3d9de70716e52db9b4701a055f8fa9.2592000.1606148254.282335-22868444',
 'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT vis-faceverify_face_feature_sdk wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component',
 'session_secret': '8be57abbb2a02afb9455952481be45fc'}
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"

#添加人脸图片的url
params = "{\"image\":\"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603525108757&di=45c2d70003aa02ad826eaa54b39ea025&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201811%2F16%2F20181116195909_klmfb.thumb.700_0.jpg\",\"image_type\":\"URL\",\"face_field\":\"faceshape,facetype\"}"

access_token = '24.d97f8c781ae2e6858f8abdddb3ffd315.2592000.1606106060.282335-22868444'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()

# 返回结果
{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 7505453589651,
 'timestamp': 1603517651,
 'cached': 0,
 'result': {'face_num': 1,
  'face_list': [{'face_token': '2a053402c002961e6d4d810a0c0cbf4f',
    'location': {'left': 338.38,
     'top': 228.76,
     'width': 158,
     'height': 156,
     'rotation': 22},
    'face_probability': 1,
    'angle': {'yaw': 14.34, 'pitch': 14.33, 'roll': 18.47},
    'face_shape': {'type': 'oval', 'probability': 0.5},
    'face_type': {'type': 'human', 'probability': 0.51}}]}}
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"

#添加人脸图片的url
params = "{\"image\":\"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603566482639&di=5856cff202e3dacce478edb45391c02c&imgtype=0&src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201906%2F28%2F20190628221852_ccwqf.jpeg\",\"image_type\":\"URL\",\"face_field\":\"faceshape,facetype\"}"

access_token = '24.d97f8c781ae2e6858f8abdddb3ffd315.2592000.1606106060.282335-22868444'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()
#返回结果{'error_code': 0,
 'error_msg': 'SUCCESS',
 'log_id': 7599354510199,
 'timestamp': 1603556559,
 'cached': 0,
 'result': {'face_num': 1,
  'face_list': [{'face_token': 'f1a44ed67ac1ad5f0212350e0759d2ed',
    'location': {'left': 343.96,
     'top': 758.89,
     'width': 333,
     'height': 323,
     'rotation': -5},
    'face_probability': 1,
    'angle': {'yaw': -18.31, 'pitch': -4.13, 'roll': -10.95},
    'face_shape': {'type': 'square', 'probability': 0.53},
    'face_type': {'type': 'human', 'probability': 0.85}}]}}
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"

params = "[{\"image\": \"2a053402c002961e6d4d810a0c0cbf4f\", \"image_type\": \"FACE_TOKEN\"}, {\"image\": \"f1a44ed67ac1ad5f0212350e0759d2ed\", \"image_type\": \"FACE_TOKEN\"}]"

access_token = '24.d97f8c781ae2e6858f8abdddb3ffd315.2592000.1606106060.282335-22868444'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    print (response.json())
#返回结果{'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 4525559900105, 'timestamp': 1603556824, 'cached': 0, 'result': {'score': 20.77251434, 'face_list': [{'face_token': '2a053402c002961e6d4d810a0c0cbf4f'}, {'face_token': 'f1a44ed67ac1ad5f0212350e0759d2ed'}]}}

二、计算机视觉

1. 远程图像

# 调用所需模块
import requests
import matplotlib.pyplot as plt
import json
from PIL import Image
from io import BytesIO
# import requests

%matplotlib inline
import matplotlib.pyplot as plt
import json
from PIL import Image


#记住是新建一个计算机视觉资源,而非人脸的那个!
endpoint = "https://colleenyee.cognitiveservices.azure.com/"# 将密钥和终结点添加到环境变量中

subscription_key = "e27e2f7a5a2448dba3c64bf4fc898e2e"# 输入密钥

analyze_url = endpoint + "vision/v3.1/analyze"   #https://cvhzx.cognitiveservices.azure.com/vision/v3.1/analyze

# 放置图片url
image_url = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2648083114,791155285&fm=26&gp=0.jpg" 
# 请求头部信息
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
# 请求参数
params = {'visualFeatures': 'Categories,Description,Color'}
# 请求主题Body
data = {'url': image_url}
response = requests.post(analyze_url, headers=headers,
                         params=params, json=data)
response.raise_for_status()

analysis = response.json()
print(json.dumps(response.json()))
image_caption = analysis["description"]["captions"][0]["text"].capitalize()

image = Image.open(BytesIO(requests.get(image_url).content))
plt.imshow(image)
plt.axis("off")
_ = plt.title(image_caption, size="x-large", y=-0.1)
plt.show()

返回结果

输入图片说明

2. 本地图像

import os
import sys
import requests
%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO

# Set image_path to the local path of an image that you want to analyze.
image_path = "/Users/19654/Desktop/renjian.JPG"
# Read the image into a byte array
image_data = open(image_path, "rb").read()
headers = {'Ocp-Apim-Subscription-Key': "e27e2f7a5a2448dba3c64bf4fc898e2e",
           'Content-Type': 'application/octet-stream'}
params = {'visualFeatures': 'Categories,Description,Color'}
response = requests.post(
    analyze_url, headers=headers, params=params, data=image_data)
response.raise_for_status()

# The 'analysis' object contains various fields that describe the image. The most
# relevant caption for the image is obtained from the 'description' property.
analysis = response.json()
print(analysis)
image_caption = analysis["description"]["captions"][0]["text"].capitalize()

# Display the image and overlay it with the caption.
image = Image.open(BytesIO(image_data))
plt.imshow(image)
plt.axis("off")
_ = plt.title(image_caption, size="x-large", y=-0.1)

返回结果

输入图片说明

3. 缩略图

import os
import sys
import requests
import matplotlib.pyplot as plt                  #用import调用所需要的模块
from PIL import Image
from io import BytesIO
                                                  #HTTP (更换自己的终结点)
thumbnail_url = "https://colleenyee.cognitiveservices.azure.com/" + "vision/v2.1/generateThumbnail"
                                                 #放入自己想要压缩的图片
image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603533198714&di=b33b64c49ef3549315ec626499f0a3a4&imgtype=0&src=http%3A%2F%2Fimg.article.pchome.net%2F00%2F42%2F71%2F22%2Fpic_lib%2Fs960x639%2F02s960x639.jpg"
                                                 #请求的头部信息
headers = {'Ocp-Apim-Subscription-Key': "e27e2f7a5a2448dba3c64bf4fc898e2e"}
                                                #请求的body
params = {'width': '100', 'height': '100', 'smartCropping': 'true'}     #这里填写想要压缩图片的尺寸
data = {'url': image_url}
response = requests.post(thumbnail_url, headers=headers,params=params, json=data)
response.raise_for_status()
thumbnail = Image.open(BytesIO(response.content))
plt.imshow(thumbnail)
plt.axis("off")
print("Thumbnail is {0}-by-{1}".format(*thumbnail.size))

返回结果

输入图片说明 原图展示

4. 提取和印刷手写

import json
import os
import sys
import requests
import time
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from PIL import Image
from io import BytesIO

text_recognition_url = endpoint + "/vision/v3.0/read/analyze"

# Set image_url to the URL of an image that you want to recognize.
image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603533798480&di=2f4e4ffff06d0abef8fa15acbc72f803&imgtype=0&src=http%3A%2F%2Fwww.niuyingyu.cn%2Fuploads%2Fallimg%2F170107%2F18-1F10H1002MO.jpg"

headers = {'Ocp-Apim-Subscription-Key': "e27e2f7a5a2448dba3c64bf4fc898e2e"}
data = {'url': image_url}
response = requests.post(text_recognition_url, headers=headers, json=data)
response.raise_for_status()

# Extracting text requires two API calls: One call to submit the
# image for processing, the other to retrieve the text found in the image.

# Holds the URI used to retrieve the recognized text.
operation_url = response.headers["Operation-Location"]

# The recognized text isn't immediately available, so poll to wait for completion.
analysis = {}
poll = True
while (poll):
    response_final = requests.get(
        response.headers["Operation-Location"], headers=headers)
    analysis = response_final.json()
    
    print(json.dumps(analysis, indent=4))

    time.sleep(1)
    if ("analyzeResult" in analysis):
        poll = False
    if ("status" in analysis and analysis['status'] == 'failed'):
        poll = False

polygons = []
if ("analyzeResult" in analysis):
    # Extract the recognized text, with bounding boxes.
    polygons = [(line["boundingBox"], line["text"])
                for line in analysis["analyzeResult"]["readResults"][0]["lines"]]

# Display the image and overlay it with the extracted text.
image = Image.open(BytesIO(requests.get(image_url).content))
ax = plt.imshow(image)
for polygon in polygons:
    vertices = [(polygon[0][i], polygon[0][i+1])
                for i in range(0, len(polygon[0]), 2)]
    text = polygon[1]
    patch = Polygon(vertices, closed=True, fill=False, linewidth=2, color='y')
    ax.axes.add_patch(patch)
    plt.text(vertices[0][0], vertices[0][1], text, fontsize=20, va="top")
plt.show()

返回结果

输入图片说明

5. 使用域模型

5.1. 地域标识

import os
import sys
import requests
%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
subscription_key='e27e2f7a5a2448dba3c64bf4fc898e2e'
landmark_analyze_url = 'https://colleenyee.cognitiveservices.azure.com/' + "vision/v3.1/models/landmarks/analyze"

# Set image_url to the URL of an image that you want to analyze.
image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603534642030&di=7ab7ea3b2ddd6438bfcdc5093414bfbe&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Ftransform%2F20141223%2Fcczmvun4306433.jpg"
headers = {'Ocp-Apim-Subscription-Key': "e27e2f7a5a2448dba3c64bf4fc898e2e"}
params = {'model': 'landmarks'}
data = {'url': image_url}
response = requests.post(
    landmark_analyze_url, headers=headers, params=params, json=data)
response.raise_for_status()

# The 'analysis' object contains various fields that describe the image. The
# most relevant landmark for the image is obtained from the 'result' property.
analysis = response.json()
assert analysis["result"]["landmarks"] is not []
print(analysis)
landmark_name = analysis["result"]["landmarks"][0]["name"].capitalize()

# Display the image and overlay it with the landmark name.
image = Image.open(BytesIO(requests.get(image_url).content))
plt.imshow(image)
plt.axis("off")
_ = plt.title(landmark_name, size="x-large", y=-0.1)
plt.show()

返回结果

输入图片说明

5.2 名人识别

import requests
%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO

# Replace <Subscription Key> with your valid subscription key.
subscription_key = "e27e2f7a5a2448dba3c64bf4fc898e2e"
assert subscription_key

vision_base_url = "https://colleenyee.cognitiveservices.azure.com/vision/v2.1/"

celebrity_analyze_url = vision_base_url + "models/celebrities/analyze"

# Set image_url to the URL of an image that you want to analyze.
image_url = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2727414015,2014118630&fm=26&gp=0.jpg"


headers = {'Ocp-Apim-Subscription-Key': subscription_key}
params = {'model': 'celebrities'}
data = {'url': image_url}
response = requests.post(
    celebrity_analyze_url, headers=headers, params=params, json=data)
response.raise_for_status()

# The 'analysis' object contains various fields that describe the image. The
# most relevant celebrity for the image is obtained from the 'result' property.
analysis = response.json()
assert analysis["result"]["celebrities"] is not []
print(analysis)
celebrity_name = analysis["result"]["celebrities"][0]["name"].capitalize()

# Display the image and overlay it with the celebrity name.
image = Image.open(BytesIO(requests.get(image_url).content))
plt.imshow(image)
plt.axis("off")
_ = plt.title(celebrity_name, size="x-large", y=-0.1)
plt.show()

返回结果

输入图片说明

三、学习心得

- 会读

API文档查询与使用都需要耐心认真,特别是对于刚入门的崽子们(包括我),觉得很难,而且无从下手,从踩坑大户变成能读懂一点点的小白,是需要花时间专注研究的,坚持很重要!

- 会看

会看是指会观察和会比对,API文档所提供的参考代码是需要修改的,比如KEY等。以及401,404,400是小白入门经常看到的状态码,要看懂API文档所提供的状态码的含义,这样才能解决报错问题,看到心心念念的200!

- 会用

使用API文档所提供的代码需要根据提示使用,不能滥用,不然随随便便就error了。

- 会套用/通用

学会读懂一种API文档后,可以尝试阅读其他API来检验自己,如Azure&Face++&百度AI人脸检测。

空文件

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/chen_ke_715/api_homework.git
git@gitee.com:chen_ke_715/api_homework.git
chen_ke_715
api_homework
API_homework
master

搜索帮助