1、 Detect whether there is a face in the picture , If so, print the face area
# encoding:utf-8
import base64
import json
import requests
'''
obtain access_token function
'''
def get_access_token(client_id="3bbdU8i9o7bMg4Wg0KSbNamr", client_secret="GvesuaedzQucRZdvgf9FikS57yc00xMd"):
# client_id Obtained for the official website AK, client_secret Obtained for the official website 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()))
# Access the token password given by the server
print(response.json()["access_token"])
return response.json()["access_token"]
'''
Face detection and attribute analysis
'''
# Requested URL
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
# The way of image processing
img_file = open("lyf.jpg", "rb")
img_base64 = base64.b64encode(img_file.read())
# print(img_base64,type(img_base64))
# Request parameters
params = {
"image": str(img_base64,'utf-8'), # Strong go str serialize , Remember to add coding format
"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']
# If result There is , Indicates that there is a face
if result:
# Get the face area
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、 utilize opencv Frame the face area
# Frame the face range
img_mat=cv2.imread("lyf.jpg")# Read the picture
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()