欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 图像人脸与视频人脸匹配度检测

图像人脸与视频人脸匹配度检测

2025/5/17 0:02:37 来源:https://blog.csdn.net/Ppandaer/article/details/142769844  浏览:    关键词:图像人脸与视频人脸匹配度检测
import cv2
import dlib
import numpy as np
import os
from pathlib import Path# 加载预训练模型
face_recognition_model = "dlib_face_recognition_resnet_model_v1.dat"
face_recognition_net = dlib.face_recognition_model_v1(face_recognition_model)detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")def load_image(file_path):"""加载图像"""image = cv2.imread(file_path)return imagedef get_face_encoding(image):"""获取图像中第一个脸部的编码"""face_rects, scores, idx = detector.run(image, 1)if len(face_rects) > 0:shape = predictor(image, face_rects[0])return np.array(face_recognition_net.compute_face_descriptor(image, shape, 100))return Nonedef compare_faces(known_face_encoding, unknown_image_path):"""比较两张图像是否属于同一人"""unknown_image = load_image(unknown_image_path)unknown_face_encoding = get_face_encoding(unknown_image)if known_face_encoding is not None and unknown_face_encoding is not None:distance = np.linalg.norm(known_face_encoding - unknown_face_encoding)threshold = 0.3  # 根据实际情况调整阈值return distance <= thresholdreturn Falsedef extract_first_frame(video_path):"""从视频中提取第一帧"""cap = cv2.VideoCapture(str(video_path))ret, frame = cap.read()if not ret:raise ValueError(f"Failed to read the video {video_path}")return framedef main():# 定义目标目录TARGET_DIR = "special"os.makedirs(TARGET_DIR, exist_ok=True)# 加载参考图像known_image_path = "example.png"  # 请替换为你的样例图片路径known_image = load_image(known_image_path)known_face_encoding = get_face_encoding(known_image)# 遍历当前目录下的所有直接子文件中的 MP4 文件for mp4_file in Path('.').iterdir():if mp4_file.is_file() and mp4_file.suffix.lower() == '.mp4':try:# 从视频中提取第一帧frame = extract_first_frame(mp4_file)# 将第一帧保存为临时文件以便后续处理temp_image_path = "temp_frame.jpg"cv2.imwrite(temp_image_path, frame)# 比较第一帧中的人脸是否与参考图像中的人脸匹配if compare_faces(known_face_encoding, temp_image_path):print(f"Face in {mp4_file.name} matches the reference image.")# 移动匹配的视频到 special 文件夹mp4_file.rename(Path(TARGET_DIR) / mp4_file.name)else:print(f"Face in {mp4_file.name} does not match the reference image.")# 清理临时文件os.remove(temp_image_path)except Exception as e:print(f"Error processing {mp4_file.name}: {str(e)}")if __name__ == "__main__":main()

wget依赖包:
shape_predictor_68_face_landmarks.dat
dlib_face_recognition_resnet_model_v1.dat

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词