# api-homework
**Repository Path**: bunnyyang73/api-homework
## Basic Information
- **Project Name**: api-homework
- **Description**: api作业
- **Primary Language**: Python
- **License**: AFL-3.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2020-10-23
- **Last Updated**: 2021-01-28
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# api-homework
* [一、面部检测](#detect)
* [二、aruze人脸识别](#face)
* [三、face++](#faceplus)
* [四、百度智能云](#baiduface)
* [五、计算机视觉](#pcversion)
* [六、学习人脸识别和计算机视觉心得体会](#experience)
一、面部检测
```
# A-1 面部检测
import requests
import json
# set to your own subscription key value
subscription_key = "20501bb040334b57bb325f64688252b0"
assert subscription_key
# replace with the string from your endpoint URL
face_api_url = 'https://bunnyyang73.cognitiveservices.azure.com/face/v1.0/detect'
# 请求正文body
image_url = 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1372683257,2188709301&fm=26&gp=0.jpg'
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": "f73d674b-1676-420e-bd1b-c5a09f38cd3d", "faceRectangle": {"top": 135, "left": 107, "width": 186, "height": 186}, "faceAttributes": {"smile": 0.0, "headPose": {"pitch": -4.1, "roll": 3.8, "yaw": -17.2}, "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": 0.894, "sadness": 0.106, "surprise": 0.0}, "blur": {"blurLevel": "low", "value": 0.0}, "exposure": {"exposureLevel": "goodExposure", "value": 0.67}, "noise": {"noiseLevel": "low", "value": 0.0}, "makeup": {"eyeMakeup": true, "lipMakeup": false}, "accessories": [], "occlusion": {"foreheadOccluded": false, "eyeOccluded": false, "mouthOccluded": false}, "hair": {"bald": 0.03, "invisible": false, "hairColor": [{"color": "blond", "confidence": 0.97}, {"color": "brown", "confidence": 0.95}, {"color": "red", "confidence": 0.27}, {"color": "gray", "confidence": 0.19}, {"color": "black", "confidence": 0.18}, {"color": "other", "confidence": 0.09}, {"color": "white", "confidence": 0.0}]}}}]'
json转译
# A-2
results = response.json()
results
[{'faceId': 'f73d674b-1676-420e-bd1b-c5a09f38cd3d',
'faceRectangle': {'top': 135, 'left': 107, 'width': 186, 'height': 186},
'faceAttributes': {'smile': 0.0,
'headPose': {'pitch': -4.1, 'roll': 3.8, 'yaw': -17.2},
'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': 0.894,
'sadness': 0.106,
'surprise': 0.0},
'blur': {'blurLevel': 'low', 'value': 0.0},
'exposure': {'exposureLevel': 'goodExposure', 'value': 0.67},
'noise': {'noiseLevel': 'low', 'value': 0.0},
'makeup': {'eyeMakeup': True, 'lipMakeup': False},
'accessories': [],
'occlusion': {'foreheadOccluded': False,
'eyeOccluded': False,
'mouthOccluded': False},
'hair': {'bald': 0.03,
'invisible': False,
'hairColor': [{'color': 'blond', 'confidence': 0.97},
{'color': 'brown', 'confidence': 0.95},
{'color': 'red', 'confidence': 0.27},
{'color': 'gray', 'confidence': 0.19},
{'color': 'black', 'confidence': 0.18},
{'color': 'other', 'confidence': 0.09},
{'color': 'white', 'confidence': 0.0}]}}}]
```
二、aruze人脸识别
### (1).Azure 认知服务-人脸演示
#### 1.create facelist
```import requests
# 1、create 列表
# faceListId
faceListId = "yws"#学生填写
create_facelists_url = 'https://bunnyyang73.cognitiveservices.azure.com/face/v1.0/facelists/{}' #学生填写
subscription_key = '20501bb040334b57bb325f64688252b0'#学生填写
assert subscription_key
headers = {
# Request header
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscription_key,
}
data = {
# 学生填写
"name": "exo",
"userData": "照片",
"recognitionModel": "recognition_03",
}
r_create = requests.put(create_facelists_url.format(faceListId),headers=headers,json=data) #学生填写
r_create
r_create.content
b''
```
#### 2.Add face 请求成功200 返回persistedFaceId
```add_face_url ="https://api-hjq.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedfaces"
assert subscription_key
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscription_key,
}
# 人脸相片地址
img_url ="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1607580509,178125350&fm=26&gp=0.jpg"
# 人脸数据
params_add_face={
"userData":"bo xian"
}
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
```
#### 3.扩展内容,封装成函数方便多次使用
```def AddFace(img_url=str,userData=str):
add_face_url ="https://api-hjq.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("http://huangjieqi.gitee.io/picture_storage/Autumnhui.jpg","丘天惠")
AddFace("http://huangjieqi.gitee.io/picture_storage/L-Tony-info.jpg","林嘉茵")
AddFace("http://huangjieqi.gitee.io/picture_storage/TLINGP.jpg","汤玲萍")
AddFace("http://huangjieqi.gitee.io/picture_storage/WenYanZeng.jpg","曾雯燕")
AddFace("http://huangjieqi.gitee.io/picture_storage/XIEIC.jpg","谢依希")
AddFace("http://huangjieqi.gitee.io/picture_storage/YuecongYang.png","杨悦聪")
AddFace("http://huangjieqi.gitee.io/picture_storage/Zoezhouyu.jpg","周雨")
AddFace("http://huangjieqi.gitee.io/picture_storage/crayon-heimi.jpg","刘瑜鹏")
AddFace("http://huangjieqi.gitee.io/picture_storage/jiayichen.jpg","陈嘉仪")
AddFace("http://huangjieqi.gitee.io/picture_storage/kg2000.jpg","徐旖芊")
AddFace("http://huangjieqi.gitee.io/picture_storage/liuxinrujiayou.jpg","刘心如")
AddFace("http://huangjieqi.gitee.io/picture_storage/liuyu19.png","刘宇")
AddFace("http://huangjieqi.gitee.io/picture_storage/ltco.jpg","李婷")
AddFace("http://huangjieqi.gitee.io/picture_storage/lucaszy.jpg","黄智毅")
AddFace("http://huangjieqi.gitee.io/picture_storage/pingzi0211.jpg","黄慧文")
AddFace("http://huangjieqi.gitee.io/picture_storage/shmimy-cn.jpg","张铭睿")
AddFace("http://huangjieqi.gitee.io/picture_storage/yichenting.jpg","陈婷")
AddFace("http://huangjieqi.gitee.io/picture_storage/coco022.jpg","洪可凡")
AddFace("http://huangjieqi.gitee.io/picture_storage/lujizhi.png","卢继志")
AddFace("http://huangjieqi.gitee.io/picture_storage/zzlhyy.jpg","张梓乐")
```
#### 4.检测人脸
```face_api_url = 'https://api-hjq.cognitiveservices.azure.com/face/v1.0/detect'
image_url = 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1607580509,178125350&fm=26&gp=0.jpg'
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
# 请求参数
params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
# 选择模型
'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})
response.json()
```
#### 5.返回人脸相似置信度
```findsimilars_url = "https://api-hjq.cognitiveservices.azure.com/face/v1.0/findsimilars"
# 请求正文 faceID需要先检测一张照片获取
data_findsimilars = {
"faceId":"1923431-83d5-4d21-8917-d3923945b39", #取上方的faceID
"faceListId": "list_003",
"maxNumOfCandidatesReturned": 10,
"mode": "matchFace" #matchPerson #一种为验证模式,一种为相似值模式
}
r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)
r_findsimilars.json()
# 查看列表
get_facelist_url = "https://api-hjq.cognitiveservices.azure.com/face/v1.0/facelists/{}"
r_get_facelist = requests.get(get_facelist_url.format(faceListId),headers=headers)
r_get_facelist.json()```
#### 6.用Pandas简化数据
```import pandas as pd
# 返回facelist数据
adf = pd.json_normalize(r_get_facelist.json()["persistedFaces"])
adf
# 返回相似度数据
bdf = pd.json_normalize(r_findsimilars.json())# 升级pandas才能运行
bdf
#合并
pd.merge(adf, bdf,how='inner', on='persistedFaceId').sort_values(by="confidence",ascending = False)
```
#### 7.删除人脸/人脸列表
```faceListId = "list_004" # 需要删除的人脸列表
# 删除列表内人脸
delete_face_url = "https://api-hjq.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedfaces/{}"
assert subscription_key
# 获取上面的persistedFaceId
persistedFaceId = r_add_face.json()["persistedFaceId"]
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscription_key,
}
# 注意requests请求为delete
r_delete_face = requests.delete(delete_face_url.format(faceListId,persistedFaceId),headers=headers)
```
三、face++
#### 1.先导入需要的模块
```
import requests
# 1.输入我们api_secret、api_key
api_secret = 'hfjLbyLs6jSNlSBej4w02PpczNV-21Q8'
api_key = 'JQQHhD4ZQshkK1u97tM0Uf2oWqgFD4Kz'
# 2. FaceSet Create
import requests,json
display_name = "exo"
outer_id = "00001"
user_data = "12男生"
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()
out:'request_id': '1603507962,bdef4b4a-7d96-435d-b27c-dc7483c91c21',
'time_used': 44,
'error_message': 'MISSING_ARGUMENTS: image_url, image_file, image_base64'}
# 3.FaceSet GetDetail(获取人脸集合信息)
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()
out:'time_used': 66,
'error_message': 'INVALID_OUTER_ID',
# 4.FaceSet AddFace(增加人脸信息)
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()
out:{'time_used': 77,
'error_message': 'INVALID_FACESET_TOKEN',
'request_id': '1603508123,028629c3-36ed-47bb-9ffa-3934adecdb7c'}
# 4.Compare Face(对比人脸相似度)
boxian1= "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1630553453,1986983804&fm=26&gp=0.jpg"
boxian2 = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3978858734,1353041964&fm=26&gp=0.jpg"
boxian3 = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2460245688,1980966382&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':boxian1,
'image_url2':boxian2
}
r = requests.post(Compare_url,params=payload)
r.json()
out:{'faces1': [{'face_rectangle': {'width': 124,
'top': 102,
'left': 212,
'height': 124},
'face_token': '3a86c73a7e962cf34da3854f5af8de7b'}],
'faces2': [{'face_rectangle': {'width': 155,
'top': 97,
'left': 182,
'height': 155},
'face_token': '4617e5c081fc37b5e4343a333e0d624a'}],
'time_used': 735,
'thresholds': {'1e-3': 62.327, '1e-5': 73.975, '1e-4': 69.101},
'confidence': 88.617,
'image_id2': 'ehmoN0mD8Mco5WVFw/NoPw==',
'image_id1': 'mi3Vf+R0IPd4z8jBgvmRoQ==',
'request_id': '1603508533,992287e0-d053-461e-8f86-fd76f87fd030'}
```
四、百度智能云人脸识别
```
import requests
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'
client_id = "cHYK5CNNevgFeH5ZSiiH4pMW"
client_secret = "aKnIoMGz0zgDpy6HhQG8qxvlRHyMavQ2"
response = requests.get(host.format(client_id, client_secret))
if response:
print(response.json())
out:{'refresh_token': '25.ffe550be01fc059ee749f3b88c8bd6da.315360000.1918893922.282335-22869751', 'expires_in': 2592000, 'session_key': '9mzdXRIcoWKFtQAKU1tGecb5Ygnn6+WQ6uQFdKHmcVp3xu3sn5wVyTnOP9UmtKr+qRp6GHBaGc2MohbHve395ZDbwKIlNg==', 'access_token': '24.ff34008bdc4e671770805d8c89de2619.2592000.1606125922.282335-22869751', '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': '2f1112e0c88138469a69d977f243ce63'}
o
```
1.人脸检测与属性分析
```
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
params = "{\"image\":\"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1172887705,1415254968&fm=26&gp=0.jpg\",\"image_type\":\"URL\",\"face_field\":\"faceshape,facetype\"}"
# image_type 图片类型:BASE64;URL;FACE_TOKEN。
access_token = '24.6d684a22feb8384590448aa0f4edcb8e.2592000.1605596154.282335-22838595' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()
out:{'error_code': 0,
'error_msg': 'SUCCESS',
'log_id': 8494751011599,
'timestamp': 1603534645,
'cached': 0,
'result': {'face_num': 1,
'face_list': [{'face_token': '419d9ad27ec44dc4fb8e1f8e21b76486',
'location': {'left': 317.8,
'top': 244.79,
'width': 35,
'height': 32,
'rotation': -47},
'face_probability': 0.83,
'angle': {'yaw': -17.44, 'pitch': 16.06, 'roll': -43.42},
'face_shape': {'type': 'round', 'probability': 0.65},
'face_type': {'type': 'human', 'probability': 0.96}}]}}
```
2.人脸对比
```
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"
params = "[{\"image\": \"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1172887705,1415254968&fm=26&gp=0.jpg", \"image_type\": \"URL\", \"face_type\": \"CERT\", \"quality_control\": \"LOW\"}, {\"image\": \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603015508446&di=eee4e2c852d804bc3b80a719df3df9ef&imgtype=0&src=http%3A%2F%2Fimg2-cloud.itouchtv.cn%2Ftvtouchtv%2Fimage%2F20170914%2F1505363583630378.jpg\", \"image_type\": \"URL\", \"face_type\": \"LIVE\", \"quality_control\": \"LOW\"}]"
# face_type 人脸的类型 LIVE;IDCARD;WATERMARK;CERT;INFRARED。
access_token = '24.6d684a22feb8384590448aa0f4edcb8e.2592000.1605596154.282335-22838595' # 调用鉴权接口获取的token
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
response.json()
out:# {'error_code': 0,
# 'error_msg': 'SUCCESS',
# 'log_id': 7999101259975,
# 'timestamp': 1603006489,
# 'cached': 0,
# 'result': {'score': 94.37832642,
# 'face_list': [{'face_token': '91cf0a5aa45b0371989e56760b30548c'},
# {'face_token': '93d2501e1cb1685c26107d0b19cc854a'}]}}
```
五、计算机视觉
1.分析远程图像
```
import requests
%matplotlib inline
import matplotlib.pyplot as plt
import json
from PIL import Image
from io import BytesIO
endpoint = "https://pcversion.cognitiveservices.azure.com/"
subscription_key = "468d759e28ae4bea824458a8751f20d4"
# base url
analyze_url = endpoint+ "vision/v3.1/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=1603520336882&di=8c4b953c072df82f1411d21db6969837&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201503%2F27%2F20150327225215_QukuZ.jpeg"
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()
# 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(json.dumps(response.json()))
image_caption = analysis["description"]["captions"][0]["text"].capitalize()
# Display the image and overlay it with the caption.
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()
{"categories": [{"name": "building_", "score": 0.9140625, "detail": {"landmarks": [{"name": "Eiffel Tower", "confidence": 0.9992201328277588}]}}], "color": {"dominantColorForeground": "Grey", "dominantColorBackground": "Grey", "dominantColors": ["Grey"], "accentColor": "837248", "isBwImg": false, "isBWImg": false}, "description": {"tags": ["outdoor", "sky", "building", "tower", "stone"], "captions": [{"text": "a tall metal tower with Eiffel Tower in the background", "confidence": 0.44687342643737793}]}, "requestId": "95c6c9b4-05ce-4713-b95f-1eb7240af6dd", "metadata": {"height": 854, "width": 480, "format": "Jpeg"}}
```

2.分析本地图片
```
import os
import sys
import requests
# If you are using a Jupyter notebook, uncomment the following line.
# %matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
# Add your Computer Vision subscription key and endpoint to your environment variables.
# if 'COMPUTER_VISION_SUBSCRIPTION_KEY' in os.environ:
# subscription_key = os.environ['COMPUTER_VISION_SUBSCRIPTION_KEY']
# else:
# print("\nSet the COMPUTER_VISION_SUBSCRIPTION_KEY environment variable.\n**Restart your shell or IDE for changes to take effect.**")
# sys.exit()
# if 'COMPUTER_VISION_ENDPOINT' in os.environ:
# endpoint = os.environ['COMPUTER_VISION_ENDPOINT']
# analyze_url = endpoint + "vision/v2.1/analyze"
# Set image_path to the local path of an image that you want to analyze.
image_path = "sz.jpg"
# Read the image into a byte array
image_data = open(image_path, "rb").read()
headers = {'Ocp-Apim-Subscription-Key': "468d759e28ae4bea824458a8751f20d4",
'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)
{'categories': [{'name': 'outdoor_', 'score': 0.0078125, 'detail': {'landmarks': []}}, {'name': 'outdoor_waterside', 'score': 0.796875, 'detail': {'landmarks': []}}], 'color': {'dominantColorForeground': 'Grey', 'dominantColorBackground': 'Black', 'dominantColors': ['Black', 'Grey'], 'accentColor': '2A71A1', 'isBwImg': False, 'isBWImg': False}, 'description': {'tags': ['water', 'outdoor', 'tree', 'boat', 'house', 'lake', 'pond', 'nature', 'docked', 'old', 'surrounded', 'waterside', 'lined', 'resort', 'several'], 'captions': [{'text': 'a pond with a house and trees around it', 'confidence': 0.3731369376182556}]}, 'requestId': 'f64657ac-8807-46e8-aa67-f2b102eae2c4', 'metadata': {'height': 220, 'width': 593, 'format': 'Jpeg'}}
```

3.生成缩略图
```
import os
import sys
import requests
# If you are using a Jupyter notebook, uncomment the following line.
# %matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
# Add your Computer Vision subscription key and endpoint to your environment variables.
# if 'COMPUTER_VISION_SUBSCRIPTION_KEY' in os.environ:
# subscription_key = os.environ['COMPUTER_VISION_SUBSCRIPTION_KEY']
# else:
# print("\nSet the COMPUTER_VISION_SUBSCRIPTION_KEY environment variable.\n**Restart your shell or IDE for changes to take effect.**")
# sys.exit()
# if 'COMPUTER_VISION_ENDPOINT' in os.environ:
# endpoint = os.environ['COMPUTER_VISION_ENDPOINT']
thumbnail_url = "https://pcversion.cognitiveservices.azure.com/" + "vision/v2.1/generateThumbnail"
# Set image_url to the URL of an image that you want to analyze.
image_url = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1416271079,4262741207&fm=26&gp=0.jpg"
headers = {'Ocp-Apim-Subscription-Key': "468d759e28ae4bea824458a8751f20d4"}
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))
# Display the thumbnail.
plt.imshow(thumbnail)
plt.axis("off")
# Verify the thumbnail size.
print("Thumbnail is {0}-by-{1}".format(*thumbnail.size))
```
Thumbnail is 100-by-100

六、学习人脸识别和计算机视觉心得体会
* API(Application Programming Interface,应用程序接口)是一些预先定义的函数,或指软件系统不同组成部分衔接的约定。 [1] 用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节。基于互联网的应用正变得越来越普及,在这个过程中,有更多的站点将自身的资源开放给开发者来调用。对外提供的API 调用使得站点之间的内容关联性更强,同时这些开放的平台也为用户、开发者和中小网站带来了更大的价值。
* api对于我来言是有挑战性的。不知何时蹦出来的401,400,还有明明今天是200,下一次又变化的400。真的非常考验我的心态。唯有不断试错,才能除错。在这个过程里,我的python代码能力也在不断提升。其次,查看api文档的能力也很重要,老师只是带进门,主要内容还是需要自己摸索。