照片识别人脸

import requests
import base64
import json
import cv2
# 请求网址
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
# 因为图片是二进制流,所以需要转换为base64格式
with open('1.jpg','rb') as f:
base64_data = base64.b64encode(f.read())
image64data = base64_data.decode()
# post请求需要传递的参数
params = {'image':image64data,'image_type':'BASE64','face_field':'landmark150'}
# url中需要的token值
access_token = '24.98a7279f2b40afdca84975c2132b61ff.2592000.1565942701.282335-16822507'
# url拼接
request_url = request_url + "?access_token=" + access_token
headers = {'Content-Type':'application/json'}
response = requests.post(url=request_url,headers=headers,data=params)
if response:
# 因为是json字符串,取值需要转换格式,所以直接使用response.json()方法
data = response.json()
# 取值
result = data['result']
# 判断有请求到数据,并且脸部数量为1
if result and result['face_num']==1:
location = result['face_list'][0]['location']
# 使用vc2模块,vc2模块是编辑图片的工具
image = cv2.imread('1.jpg')
# 因为传入的参数需要是int类型的,所有强转为int
left = int(location['left'])
top = int(location['top'])
width = int(location['width'])
height = int(location['height'])
#利用cv2绘制人脸矩形框
#参数:人脸数据,(人脸左侧位置,人脸顶部位置)(人脸右侧位置,人脸下部位置)(颜色值)
cv2.rectangle(image,(left,top),(left+width,top+height),(0,0,255),1)
# 将绘制好的图片存入到文件夹
cv2.imwrite('2.jpg',image)
#绘制人脸150点位
landmark150 = result['face_list'][0]['landmark150']
points_list = []
print(landmark150)
for i in landmark150:
print(i)
points_list.append(landmark150[i])
for point in points_list:
#参数:图像,圆心坐标,点半径大小,颜色,线条粗细
x = int(point['x'])
y = int(point['y'])
cv2.circle(image,(x,y),1,(0,255,1),3)
cv2.imwrite('face150.jpg',image) #保存图片

posted on 2019-07-17 19:50  潇潇无敌  阅读(395)  评论(0编辑  收藏  举报

导航