Ready to work:
- Install opencv
- Register Baidu API application
- Get appid, app_key, secrt_key and get access_token
- Download Baidu image recognition SDK or use API call
Divided into two
core ideas:
- Use the opencv library cv2 to call the camera function, use ip to connect to the mobile phone, and get a frame of pictures in a loop.
- A frame of image saved is parsed into base64 encoded file using base64.b64encode().
- Use Baidu face recognition api or sdk, after calling the recognition result: wearing a mask, male and female, coordinates of facial features, etc.
import cv2
import base64
def capture():
url = 'rtsp://admin:[email protected]: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()
Run code rendering:
through the Q key predetermined by the code, end the capture, write to the file, then convert to base64, call the api to parse, and return the data:
写入成功!
{
'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}}