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

python 复制代码
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 image

def 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 None

def 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 <= threshold
    return False

def 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 frame

def 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

相关推荐
CoookeCola25 分钟前
M.I.O: Interactive Intelligence for Digital Humans(交互式智能数字人)
论文阅读·人工智能·aigc·音视频
那雨倾城28 分钟前
用 YOLO Pose + Segmentation 在PiscCode构建“语义佛光”:一次实时视觉语义融合实验
图像处理·python·opencv·算法·yolo·计算机视觉·视觉检测
CoovallyAIHub37 分钟前
自顶向下 or 自底向上?姿态估计技术是如何进化的?
深度学习·算法·计算机视觉
CoovallyAIHub1 小时前
YOLO11算法深度解析:四大工业场景实战,开源数据集助力AI质检落地
深度学习·算法·计算机视觉
sali-tec1 小时前
C# 基于halcon的视觉工作流-章71 深度学习-预处理OCR
开发语言·人工智能·深度学习·数码相机·算法·计算机视觉·ocr
AI科技星2 小时前
光速的几何本质与运动极限:基于张祥前统一场论对光子及有质量粒子运动的统一诠释
数据结构·人工智能·经验分享·算法·计算机视觉
sali-tec2 小时前
C# 基于halcon的视觉工具VisionTool Halcon发布
人工智能·深度学习·算法·计算机视觉·分类
Robot侠2 小时前
ROS1从入门到精通 20:性能优化与最佳实践
图像处理·人工智能·计算机视觉·性能优化·机器人·ros
编码小哥2 小时前
OpenCV仿射变换与透视变换实战
人工智能·opencv·计算机视觉
泡泡茶壶_ovo2 小时前
Zero-Shot Image Captioning with Multi-type Entity Representations(AAAI 2025)
人工智能·深度学习·计算机视觉·imagecaptioning·multimodal