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

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

相关推荐
咚咚王者29 分钟前
人工智能之视觉领域 计算机视觉 第十章 图像直方图
人工智能·opencv·计算机视觉
向哆哆3 小时前
白血病细胞与正常细胞识别数据集:医学影像与智能诊断的细胞分析数据
人工智能·目标检测·计算机视觉
youcans_7 小时前
【跟我学YOLO】YOLO26(3)安装配置与快速使用
图像处理·yolo·目标检测·计算机视觉·环境配置
吾在学习路7 小时前
AoP-SAM: Automation of Prompts for Efficient Segmentation
人工智能·深度学习·算法·计算机视觉
开开心心就好7 小时前
实用系统备份还原,小巧免PE备份快镜像小
windows·计算机视觉·pdf·计算机外设·迭代器模式·excel·桥接模式
@陈小鱼8 小时前
基于 Savitzky-Golay滤波器的超声图像运动分析方法
python·计算机视觉·matlab·信号处理
linux_cfan8 小时前
2026版 WordPress 视频插件终极选型:知识付费创作者如何低成本打造专业在线课堂?
前端·javascript·音视频·html5
REDcker9 小时前
SIP 协议原理及应用精解
音视频·ims·sip·sdp·移动通信·volte·h323
奔跑吧 android10 小时前
【车载Audio】【AudioHal 07】【高通音频架构】【从逻辑策略到物理执行】
音视频·audio·aosp·android15·8295·音频子系统
啊阿狸不会拉杆10 小时前
《计算机视觉:模型、学习和推理》第 4 章-拟合概率模型
人工智能·python·学习·算法·机器学习·计算机视觉·拟合概率模型