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

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

相关推荐
泡干脆面就番茄41 分钟前
03_LBPH人脸识别算法原理与实战
python·opencv
YOLO数据集集合1 小时前
天空反无人机检测数据集 | 无人机检测 多旋翼识别 固定翼识别 低空安防 目标检测9063期
人工智能·yolo·目标检测·计算机视觉·无人机·反无人机
可乐鸡翅yeah_2 小时前
hls.js 播放质量埋点实战,采集卡顿、起播、错误指标定位线上用户问题
开发语言·前端·javascript·ecmascript·音视频·m3u8·音视频在线播放
youandyouyou2 小时前
医学远程示教同屏直播的技术实现路径:以连通宝双流方案为例
音视频·网络通信
A13345553 小时前
保姆级教程:视频播放器怎么导入SRT外挂字幕
音视频
揽秀亭长3 小时前
如何把提取一个视频的脚本?实测3种提取视频脚本的方法
音视频
深度学习lover3 小时前
<数据集>蚜虫识别<目标检测>
人工智能·深度学习·yolo·目标检测·计算机视觉·蚜虫识别
开发笔记-阿牛3 小时前
嵌入式蓝牙开发:AC2005B 芯片技术解析 —— 省晶振设计、13dBm 射频与 Auracast 广播音响开发指南
人工智能·单片机·音视频
阿酷tony3 小时前
视频专栏列表的防录屏水印和跑马灯效果(也可网站调用)
java·前端·音视频
Black蜡笔小新4 小时前
运维提效!视频汇聚平台EasyCVR视频质量诊断,掉线花屏自动预警
运维·安全·音视频