# api **Repository Path**: bannngo/api ## Basic Information - **Project Name**: api - **Description**: No description available - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-10-21 - **Last Updated**: 2020-12-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 人脸识别 --- ### Azure #### 1. face detect [参考文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236) ```python import requests import json # 插入自己的key subscription_key = "aa97b62ddfc845549c70788f52bdc8f4" assert subscription_key # 放入自己的目标URL face_api_url = 'https://ijustwanttotrythis.cognitiveservices.azure.com/face/v1.0/detect' # 请求正文body image_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602674014068&di=cf0dd3f8f5590cbf1772e868e14eb21e&imgtype=0&src=http%3A%2F%2Fqqpublic.qpic.cn%2Fqq_public%2F0%2F0-2777613383-2C6DE3A3620E93FF1A43CF50D939AA7A%2F0%3Ffmt%3Djpg%26size%3D59%26h%3D427%26w%3D885%26ppv%3D1' # 请求头 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()) # json转义 results = response.json() results #[{'faceId': '819d9b1e-70a3-4b52-a4fe-74eca9b64570', # 'faceRectangle': {'top': 110, 'left': 337, 'width': 73, 'height': 73}, # 'faceAttributes': {'smile': 1.0, # 'headPose': {'pitch': 3.6, 'roll': 1.4, 'yaw': -1.3}, # 'gender': 'male', # 'age': 42.0, # 'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1}, # 'glasses': 'ReadingGlasses', # 'emotion': {'anger': 0.0, # 'contempt': 0.0, # 'disgust': 0.0, # 'fear': 0.0, # 'happiness': 1.0, # 'neutral': 0.0, # 'sadness': 0.0, # 'surprise': 0.0}, # 'blur': {'blurLevel': 'high', 'value': 1.0}, # 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.61}, # 'noise': {'noiseLevel': 'medium', 'value': 0.4}, # 'makeup': {'eyeMakeup': False, 'lipMakeup': False}, # 'accessories': [{'type': 'glasses', 'confidence': 0.97}], # 'occlusion': {'foreheadOccluded': False, # 'eyeOccluded': False, # 'mouthOccluded': False}, # 'hair': {'bald': 0.04, # 'invisible': False, # 'hairColor': [{'color': 'black', 'confidence': 1.0}, # {'color': 'brown', 'confidence': 0.91}, # {'color': 'gray', 'confidence': 0.59}, # {'color': 'other', 'confidence': 0.26}, # {'color': 'blond', 'confidence': 0.03}, # {'color': 'red', 'confidence': 0.01}, # {'color': 'white', 'confidence': 0.0}]}}} # pandas数据表格化 import pandas as pd df_face = pd.json_normalize(results) df_face ``` | faceID | faceRectangle.top | faceRectangle.left | faceRectangle.width | faceRectangle.height | faceAttributes.smile | faceAttributes.headPose.pitch | faceAttributes.headPose.roll | faceAttributes.headPose.yaw | faceAttributes.gender | faceAttributes.noise.value | faceAttributes.makeup.eyeMakeup | | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | |819d9b1e-70a3-4b52-a4fe-74eca9b64570 | 110 |337|73|73|1.000|3.6|1.4|-1.3|male |0.40|False| #### 2.facelist - 创建人脸列表 [参考文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039524b) ```python import requests faceListId = "wujing"#设置人脸列表ID create_facelists_url = "https://ijustwanttotrythis.cognitiveservices.azure.com/face/v1.0/facelists/{}" # 目标url subscription_key = "aa97b62ddfc845549c70788f52bdc8f4" #密钥 assert subscription_key # 请求头 headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': subscription_key, } # 相关信息及识别模型的选用 data = { "name": "api_face", "userData": "全都是吴京", "recognitionModel": "recognition_03", } # 发送请求 r_create = requests.put(create_facelists_url.format(faceListId),headers=headers,json=data) r_create r_create.content # b'' ⬅出现这个就是成功了 ``` - 添加人脸 [参考文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395250) ```python add_face_url = 'https://ijustwanttotrythis.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=1602864780908&di=cbb211f7fac7b5d3720cf23ffbecd9ec&imgtype=0&src=http%3A%2F%2Fimage.uczzd.cn%2F10010593502112668602.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_get_facelist.json() # 返回persistedFaceId信息 # 封装成函数更便利地添加多张人脸 ```python def AddFace(img_url=str,userData=str): add_face_url ="https://ijustwanttotrythis.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://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2222838717,2889695815&fm=26&gp=0.jpg","吴京扯衣服") AddFace("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602864780279&di=8fa1048a46f62dab4e12e0e767745275&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn21%2F545%2Fw550h795%2F20181129%2F4cfd-hpinrya8184214.jpg","吴京伸手") AddFace("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602864780277&di=ae7ca23580b9f694e150e29df08fc6ff&imgtype=0&src=http%3A%2F%2Fy0.ifengimg.com%2Fa%2F2015_16%2F10fad0a2229b295.jpg","吴京战狼") AddFace("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602864780275&di=530381406b1adc1c417a6da45801f5b4&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Ffront%2F240%2Fw640h400%2F20190311%2Fdy9s-htzuhtp9895114.jpg","吴京不雅") # 状态码返回200即成功 ``` - 删除人脸 [参考文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395251) ```python faceListId = "wujing" delete_face_url = "https://ijustwanttotrythis.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedFaces/{}" assert subscription_key persistedFaceId = "324508c9-d6b4-42de-8997-589ac83c5880" # 输入想删除的人脸persistedFaceId # 请求头 headers = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': subscription_key, } r_delete_face = requests.delete(delete_face_url.format(faceListId,persistedFaceId),headers=headers) ``` #### 3.人脸检测&Find Similars ```python # 人脸检测 face_api_url = 'https://ijustwanttotrythis.cognitiveservices.azure.com/face/v1.0/detect' # 图片地址 image_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602864780271&di=07d432e594aaaa9a17464a588b3e16da&imgtype=0&src=http%3A%2F%2Fdingyue.nosdn.127.net%2FZBh0yEfx65xqDmmC9voN7zBfxPdGmROwkdGRiIzDy0DwK1501646645923.jpg' headers = {'Ocp-Apim-Subscription-Key': subscription_key} # 请求参数 params = { 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', # 选择model 'recognitionModel':'recognition_03',#此参数需与facelist参数一致 'detectionModel':'detection_01', # 可选参数 'returnFaceAttributes': '', } response = requests.post(face_api_url, params=params, headers=headers, json={"url": image_url}) response.json() # find similars [参考文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395237) findsimilars_url = "https://ijustwanttotrythis.cognitiveservices.azure.com/face/v1.0/findsimilars" # 请求正文 faceId需要先检测一张照片获取 data_findsimilars = { "faceId":"eb26cb12-e832-4622-b95a-bfa3462e7052",#取上方的faceID "faceListId": "wujing", "maxNumOfCandidatesReturned": 10, "mode": "matchFace"#matchPerson #一种为验证模式,一种为相似值模式 } r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars) # json转义 r_findsimilars.json() # 将facelist中数据转换成pandas表格 import pandas as pd faceListId_df = pd.json_normalize(r_get_facelist.json()["persistedFaces"])# 升级pandas才能运行 faceListId_df ``` | | persistedFaceId | userData | | :---: | :---: | :---: | |0 | 627bb8e6-6288-41e1-9a9f-861c8524bcec | 吴京敬礼 | |1|dfdc32c2-2369-4c89-96cb-10b8637d87e7 |吴京扯衣服| |2|be61a28f-acb1-47a4-950e-6ce4714f6c2d |吴京伸手| |3 |564a0401-924c-4df2-ae73-bc52f5094a5b|吴京战狼| |4 |324508c9-d6b4-42de-8997-589ac83c5880 |吴京不雅| ```python # 返回相似度的数据 find_df = pd.json_normalize(r_findsimilars.json()) find_df # 将两个表格合并 pd.merge(faceListId_df, find_df,how='inner', on='persistedFaceId').sort_values(by="confidence",ascending = False) ``` | | persistedFaceId |userData |confidence| | :---: | :---: | :---: | :---: | |4 |324508c9-d6b4-42de-8997-589ac83c5880 |吴京不雅 |0.95416| |1 |dfdc32c2-2369-4c89-96cb-10b8637d87e7 |吴京扯衣服 |0.88954| |2 |be61a28f-acb1-47a4-950e-6ce4714f6c2d |吴京伸手 |0.85219| |0 |627bb8e6-6288-41e1-9a9f-861c8524bcec |吴京敬礼 |0.78757| |3 |564a0401-924c-4df2-ae73-bc52f5094a5b |吴京战狼 |0.74998| ### Face++ #### 1.face detect ```python import requests,json #导入所需模块 api_secret = "3DlGefTk5MN5LU_cHOcP_-9b-M3LrCkc" api_key = "iJ2pkfkTzsLSZG4mkUsejiuwwIJ5wSfd" #键入我们的api_secret和api_key # 目标url Detect_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' img_url = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2222838717,2889695815&fm=26&gp=0.jpg" #可选用网络图片或本地图片 # 沿用API文档的示范代码,准备我们的headers和图片(数据) headers = { 'Content-Type': 'application/json', } payload = { "image_url":img_url, 'api_key': api_key, 'api_secret': api_secret, 'return_attributes':'gender,age,smiling,emotion', # 选择返回人脸特征判断的属性 } # 发送请求 r = requests.post(Detect_url,params=payload) r.json() #详细返回数据略 ``` #### 2.face set + create ```python import requests,json api_secret = "3DlGefTk5MN5LU_cHOcP_-9b-M3LrCkc" api_key = "iJ2pkfkTzsLSZG4mkUsejiuwwIJ5wSfd" #键入我们的api_secret和api_key display_name = "吴京" # 自定义集合名字 outer_id = "00001" # 自定义标识 user_data = "全都是吴京" # 自定义信息 CreateFace_Url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create" 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_token': 'fee0e36b56116679fe8e7b083b22cd14', # 'time_used': 170, # 'face_count': 0, # 'face_added': 0, # 'request_id': '1602858358,a58c18d4-8ab1-49e8-b621-2967e4ee8074', # 'outer_id': '00001', # 'failure_detail': []} ``` + GetDetail(获取人脸集合信息) ```python 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': 'fee0e36b56116679fe8e7b083b22cd14', # 'tags': '', # 'time_used': 89, # 'user_data': '全都是吴京', # 'display_name': '吴京', # 'face_tokens': [], # 'face_count': 0, # 'request_id': '1602858376,700fa7b1-fb8f-483f-9954-d67996d3ea0b', # 'outer_id': '00001'} ``` + AddFace ```python AddFace_url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface" payload = { 'api_key': api_key, 'api_secret': api_secret, 'faceset_token':'fee0e36b56116679fe8e7b083b22cd14',# 输入在getdetail中得到的faceset_token 'face_tokens':'c292d1576427d811d1018c4490f5eede',# 输入人脸检测中得到的face_token } r = requests.post(AddFace_url,params=payload) r.json() # 返回信息略 ``` + RemoveFace ```python RemoveFace_url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/removeface" payload = { 'api_key': api_key, 'api_secret': api_secret, 'faceset_token':'fee0e36b56116679fe8e7b083b22cd14', 'face_tokens':'c292d1576427d811d1018c4490f5eede',# 输入想要删除的人脸face_tokens r = requests.post(RemoveFace_url,params=payload) r.json() } ``` + Faceset Update ```python Update_url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/update" payload = { 'api_key': api_key, 'api_secret': api_secret, 'faceset_token':'fee0e36b56116679fe8e7b083b22cd14', # 需要更新的人脸集合token 'user_data':"目前只有1吴京",# 输入需要更新的信息 } # 请求部分略 ``` #### 3.Compare Face ```python # 先输入想对比的人脸图片地址 wujing01 = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602864780908&di=cbb211f7fac7b5d3720cf23ffbecd9ec&imgtype=0&src=http%3A%2F%2Fimage.uczzd.cn%2F10010593502112668602.jpeg" wujing02 = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2222838717,2889695815&fm=26&gp=0.jpg" wujing03 = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602864780279&di=8fa1048a46f62dab4e12e0e767745275&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn21%2F545%2Fw550h795%2F20181129%2F4cfd-hpinrya8184214.jpg" # 方案1:直接对比 Compare_url = "https://api-cn.faceplusplus.com/facepp/v3/compare" payload ={ 'api_key': api_key, 'api_secret': api_secret, 'image_url1':wujing01, 'image_url2':wujing02 } # 请求部分略 # 方案2:与人脸集合进行对比 Detect_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' img_url = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2222838717,2889695815&fm=26&gp=0.jpg" payload = { "image_url":img_url, 'api_key': api_key, 'api_secret': api_secret, 'return_attributes':'gender,age,smiling,emotion', } # 同样略 ``` ### 百度云 ```python import requests # client_id 为官网获取的API Key, client_secret 为官网获取的Secret Key host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}' client_id = "7cmbzC0lIMvNtFGTUQIhn9Cm" client_secret = "1xbdVzNdktxCZYg7cOrKN7qCt8weETKh" response = requests.get(host.format(client_id, client_secret)) if response: print(response.json()) # {'refresh_token': '25.28e474eb76b22b468b28bd214b4c5f5e.315360000.1918366387.282335-22838595', # 'expires_in': 2592000, # 'session_key': '9mzdDcZhxI0DqtPikwQHIKEoKgdnFBrsLrnaN0mbUqjzpTf/BQLtOGJhjMAbUmQN3fXWr8Bp4hkjIbggmsTDGBTb0MAaIQ==', # 'access_token': '24.60f9411a4b4ea9f169195953c398a3e0.2592000.1605598387.282335-22838595', # 'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT 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': '3467d4c7825a546093e81c2d4249db92'} # 1.人脸检测与属性分析 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect" params = "{\"image\":\"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=4043599707,1953932156&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() # {'error_code': 0, # 'error_msg': 'SUCCESS', # 'log_id': 4565101254575, # 'timestamp': 1603006446, # 'cached': 0, # 'result': {'face_num': 1, # 'face_list': [{'face_token': '91cf0a5aa45b0371989e56760b30548c', # 'location': {'left': 186.93, # 'top': 99.21, # 'width': 121, # 'height': 118, # 'rotation': 1}, # 'face_probability': 1, # 'angle': {'yaw': -1.85, 'pitch': 4.67, 'roll': 0.97}, # 'face_shape': {'type': 'oval', 'probability': 0.66}, # 'face_type': {'type': 'human', 'probability': 1}}]}} # 2.人脸对比 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match" params = "[{\"image\": \"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3430692674,459091344&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() # {'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'}]}} # 3.创建用户组 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add" params = "{\"group_id\":\"group2\"}" 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() # {'error_code': 0, # 'error_msg': 'SUCCESS', # 'log_id': 2594655589842, # 'timestamp': 1603006614, # 'cached': 0, # 'result': None} # 4.人脸注册 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add" params = "{\"image\":\"91cf0a5aa45b0371989e56760b30548c\",\"image_type\":\"FACE_TOKEN\",\"group_id\":\"group1\",\"user_id\":\"user1\",\"user_info\":\"abc\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}" 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() # {'error_code': 0, # 'error_msg': 'SUCCESS', # 'log_id': 9420194001790, # 'timestamp': 1603006639, # 'cached': 0, # 'result': {'face_token': '91cf0a5aa45b0371989e56760b30548c', # 'location': {'left': 186.93, # 'top': 99.21, # 'width': 121, # 'height': 118, # 'rotation': 1}}} # 5.获取用户人脸列表 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist" params = "{\"user_id\":\"user1\",\"group_id\":\"group2\"}" 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() # {'error_code': 0, # 'error_msg': 'SUCCESS', # 'log_id': 500105794579, # 'timestamp': 1603006672, # 'cached': 0, # 'result': {'face_list': [{'face_token': '91cf0a5aa45b0371989e56760b30548c', # 'ctime': '2020-10-18 15:37:20'}]}} # 6.删除用户组 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/delete" params = "{\"group_id\":\"group1\"}" 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() # {'error_code': 0, # 'error_msg': 'SUCCESS', # 'log_id': 3589996510179, # 'timestamp': 1603006728, # 'cached': 0, # 'result': None} ``` --- # 计算机视觉 --- #### 1.分析远程图像 ```python import requests import matplotlib.pyplot as plt import json from PIL import Image from io import BytesIO endpoint = "https://seesee.api.cognitive.microsoft.com/" # 你的终端 subscription_key = "60738d9f152d426f84f72543a3146315" # 你的密钥 # 目标url analyze_url = "https://seesee.cognitiveservices.azure.com/" + "vision/v2.1/analyze" # 输入你想要分析的图片地址 image_url = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=241451007,415405648&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.分析本地图片 ```python import os import sys import requests import matplotlib.pyplot as plt from PIL import Image from io import BytesIO # 目标url analyze_url = "https://seesee.cognitiveservices.azure.com/" + "vision/v2.1/analyze" # 输入你想要分析的本地图片地址 image_path = "OIP.jpg" # Read the image into a byte array image_data = open(image_path, "rb").read() headers = {'Ocp-Apim-Subscription-Key': "dd748cf10bf9404399e5416d9399e218", '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() analysis = response.json() print(analysis) image_caption = analysis["description"]["captions"][0]["text"].capitalize() image = Image.open(BytesIO(image_data)) plt.imshow(image) plt.axis("off") _ = plt.title(image_caption, size="x-large", y=-0.1) # 返回数据略 ``` #### 3.生成缩略图 ```python import os import sys import requests # %matplotlib inline import matplotlib.pyplot as plt from PIL import Image from io import BytesIO thumbnail_url = "https://seesee.cognitiveservices.azure.com/" + "vision/v2.1/generateThumbnail" # Set image_url to the URL of an image that you want to analyze. image_url = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=241451007,415405648&fm=26&gp=0.jpg" headers = {'Ocp-Apim-Subscription-Key': "dd748cf10bf9404399e5416d9399e218"} 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)) # 同略 ``` #### 4.提取文本 ```python 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://www.apple.com.cn/v/macos/big-sur-preview/b/images/overview/messages/group_photos_static__fbox06wyksuq_large_2x.jpg" headers = {'Ocp-Apim-Subscription-Key': "ec2c3e5af3b84652a898e9d94c88a113"} 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() ``` --- ### 学习心得 上了这么多个星期的api课,每次做作业都觉得自己像**弱智**。 特别是写完这个markdown已经觉得**筋疲力尽**。 虽然但是还是觉得api课学的东西很重要要好好学,加油读书人。