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

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

相关推荐
工业设备方案笔记40 分钟前
RK3588工业视觉检测方案详解:AI如何赋能智能制造?
arm开发·人工智能·计算机视觉·目标跟踪·视觉检测·边缘计算·制造
欧特克_Glodon1 小时前
OpenCV计算机视觉开发入门与实践<七>:OpenCV 界面编程之窗口
c++·人工智能·opencv·计算机视觉
无线视频解决方案2 小时前
HDMI直出vsMIPI转接对比:AM8360D为何能省2颗芯片
音视频·无线图传·炬力北方
ai产品老杨2 小时前
边云协同视频分析性能优化指南:多站点部署下的参数配置与排查清单(边缘推理+云端管理)
性能优化·音视频
程序员老陆4 小时前
OpenGL 在视频渲染里的角色:它到底加速了什么?
音视频·gpu·opengl
熊猫钓鱼>_>4 小时前
Seedance 2.0 技术深度解析:重构AI视频生成的世界模型新范式
人工智能·笔记·ai·重构·音视频·变革·sedence2.0
弈语道破AI4 小时前
3D渲染不再熬时间!即梦 Seedance 2.5 具备3D白模渲染功能的AI视频生成工具
人工智能·3d·音视频
m0_617493944 小时前
OpenCV cv2.circle() 坐标类型错误排查与修复指南
人工智能·opencv·计算机视觉
AI创界者4 小时前
最新 ComfyUI + LTX-2.5 本地一键整合包:文生视频/图生视频/数字人全流程指南
人工智能·aigc·音视频
阿童木写作5 小时前
速卖通卖家图片翻译工具:批量图片翻译+视频字幕+智能抠图一站式搞定
大数据·人工智能·python·音视频