调用android相机,现实人脸识别
准备工作:
- 安装opencv
- 注册百度API应用
- 获取appid,app_key,secrt_key并且获取access_token
- 下载百度图像识别sdk或者使用API调用
分两大块
核心思路:
- 使用opencv库cv2调用摄像头功能,使用ip连接到手机,循环获取一帧画面。
- 保存的一帧图像 使用base64.b64encode()解析为base64编码文件。
使用百度人脸识别api或者sdk,调用后识别返回结果:戴口罩,男女,五官的坐标等等。
import cv2
import base64
def capture():url = 'rtsp://admin:admin@192.168.5.27:8554/live'
cap = cv2.VideoCapture(url) # 带有摄像头的笔记本用户将url替换为 0 即可
while(cap.isOpened()):
ret, frame = cap.read() # frame为一帧图像,当frame为空时,ret返回false,否则为true
cv2.imshow('frame',frame)
# if cv2.waitKey(1) & 0xFF == ord('r'):
# cv2.imwrite('C:/Users/Administrator/Desktop/我的照片.jpg', frame)
# print('写入成功!')
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.imwrite('C:/Users/Administrator/Desktop/my.jpg', frame)
print('写入成功!')
break
cap.release() # release the capture
cv2.destroyAllWindows()
# -------------------------------人脸检测------------------------------------------------
# encoding:utf-8
import requests
def detect():
'''
人脸检测与属性分析
'''
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
params = {
'image':file_64,
'image_type':'BASE64'
}
access_token = '24.b23aafe39fc60508b8c92a9dd38a0571.2592000.1607615861.282335-22960104'
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())
for i in response.json()['result']['face_list']:
print(i)
if __name__=='__main__':
capture()
# -------------------------------图片准备------------------------------------------------
with open('C:/Users/Administrator/Desktop/my.jpg', 'rb')as file:
file_64 = base64.b64encode(file.read())
detect()
运行代码效果图:
通过代码预定的Q键,结束捕捉,写入文件,然后转换base64,调用api解析,返回数据:
写入成功!
{
'face_token': '1f0eb2764eeb9f21c98b2a0d715deb26',
'location': {
'left': 210.46, 'top': 163.33, 'width': 182, 'height': 183, 'rotation': 0},
'face_probability': 1,
'angle': {
'yaw': 0.77, 'pitch': 4.73, 'roll': -1.05}}
还没有评论,来说两句吧...