1、检测图片是否有人脸,有的话打印人脸范围区域
# encoding:utf-8
import base64
import json
import requests
'''
获取access_token函数
'''
def get_access_token(client_id="3bbdU8i9o7bMg4Wg0KSbNamr", client_secret="GvesuaedzQucRZdvgf9FikS57yc00xMd"):
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=3bbdU8i9o7bMg4Wg0KSbNamr&client_secret=GvesuaedzQucRZdvgf9FikS57yc00xMd'
print(host)
response = requests.get(host)
if response:
print(response.json(), type(response.json()))
# 访问服务器所给的令牌口令
print(response.json()["access_token"])
return response.json()["access_token"]
'''
人脸检测与属性分析
'''
# 请求的网址
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
# 图片处理的方式
img_file = open("lyf.jpg", "rb")
img_base64 = base64.b64encode(img_file.read())
# print(img_base64,type(img_base64))
# 请求参数
params = {
"image": str(img_base64,'utf-8'), # 强转str序列化,记得加编码格式
"image_type": "BASE64",
"max_face_num": 2
}
params = json.dumps(params)
access_token = get_access_token()
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())
result=response.json()['result']
# 如果result存在,表示有人脸
if result:
# 拿到人脸区域范围
print(result['face_list'][0]['location'])
left=result['face_list'][0]['location']['left']
top = result['face_list'][0]['location']['top']
width = result['face_list'][0]['location']['width']
height = result['face_list'][0]['location']['height']
print(left,top,width,height)
2、利用opencv框出人脸区域
# 框出人脸范围
img_mat=cv2.imread("lyf.jpg")#读取图片
cv2.rectangle(img_mat,(left,top),(left+width,top+height),(0,0,255),2)
cv2.imshow("img_lyf",img_mat)
cv2.waitKey(0)
cv2.destroyAllWindows()