python语言
功能:
1、读取将第三方传入视频
2、提取人脸
3、将人脸与图片数据库进行对比
4、获取人物信息,
5、将人物信息以ymal格式递给另一接口
这个脚本会使用 OpenCV 进行视频处理和人脸检测,使用face_recognition库进行人脸特征提取和对比,最后使用PyYAML库将人物信息以 YAML 格式传递给另一个接口。
安装依赖库
在运行脚本之前,需要安装以下库:
pip install opencv-python face_recognition pyyaml requests
脚本代码
import cv2
import face_recognition
import yaml
import requests
import os
函数:从图片数据库中加载人脸编码和对应的人物信息
def load_face_database(database_path):
known_face_encodings = []
known_face_names = []
for filename in os.listdir(database_path):
if filename.endswith(('.png', '.jpg', '.jpeg')):
image_path = os.path.join(database_path, filename)
image = face_recognition.load_image_file(image_path)
face_encodings = face_recognition.face_encodings(image)
if len(face_encodings) > 0:
face_encoding = face_encodings[0]
known_face_encodings.append(face_encoding)
# 假设文件名就是人物姓名
name = os.path.splitext(filename)[0]
known_face_names.append(name)
return known_face_encodings, known_face_names
函数:处理视频并进行人脸对比
def process_video(video_path, database_path, api_url):
# 加载人脸数据库
known_face_encodings, known_face_names = load_face_database(database_path)
# 打开视频文件
cap = cv2.VideoCapture(video_path)
detected_names = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 将BGR颜色空间转换为RGB颜色空间(face_recognition库使用RGB)
rgb_frame = frame[:, :, ::-1]
# 检测当前帧中的人脸位置和编码
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for face_encoding in face_encodings:
# 对比人脸编码
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# 如果有匹配的人脸
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
if name not in detected_names:
detected_names.append(name)
# 释放视频捕获对象
cap.release()
# 将人物信息转换为YAML格式
data = {'detected_names': detected_names}
yaml_data = yaml.dump(data)
# 将YAML数据发送到另一个接口
headers = {'Content-Type': 'application/x-yaml'}
response = requests.post(api_url, data=yaml_data, headers=headers)
if response.status_code == 200:
print("人物信息已成功发送到接口。")
else:
print(f"发送信息到接口时出错,状态码: {response.status_code}")
return detected_names
主程序
if __name__ == "__main__":
video_path = "your_video.mp4" # 第三方传入的视频文件路径
database_path = "your_database_folder" # 图片数据库文件夹路径
api_url = "http://example.com/api" # 接收YAML数据的接口URL
detected_names = process_video(video_path, database_path, api_url)
print("检测到的人物姓名:", detected_names)
代码说明
1、加载人脸数据库:load_face_database函数会遍历指定文件夹中的所有图片文件,提取每张图片中的人脸编码,并将其存储在known_face_encodings列表中,同时将对应的人物姓名(假设为文件名)存储在known_face_names列表中。
2、处理视频:process_video函数会打开指定的视频文件,逐帧读取视频,检测每一帧中的人脸位置和编码,并将其与已知的人脸编码进行对比。如果有匹配的人脸,则记录对应的人物姓名。
3、将人物信息转换为 YAML 格式:使用PyYAML库将检测到的人物姓名列表转换为 YAML 格式的字符串。
发送 YAML 数据到另一个接口:使用requests库将 YAML 数据发送到指定的接口。
4、注意事项
请将video_path、database_path和api_url替换为实际的视频文件路径、图片数据库文件夹路径和接收 YAML 数据的接口 URL。
图片数据库中的图片文件名应包含人物姓名,脚本会将文件名作为人物姓名。
确保接收 YAML 数据的接口能够正确处理application/x-yaml类型的请求。