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

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

相关推荐
给大佬递杯卡布奇诺2 小时前
FFmpeg 基本API avio_open函数内部调用流程分析
c++·ffmpeg·音视频
fsnine4 小时前
YOLOv2原理介绍
人工智能·计算机视觉·目标跟踪
Damon小智4 小时前
RedPlayer 视频播放器在 HarmonyOS 应用中的实践
音视频·harmonyos·鸿蒙·小红书·三方库·redplayer
云雾J视界6 小时前
Linux企业级解决方案架构:字节跳动短视频推荐系统全链路实践
linux·云原生·架构·kubernetes·音视频·glusterfs·elk stack
m0_650108246 小时前
【论文精读】FlowVid:驯服不完美的光流,实现一致的视频到视频合成
人工智能·计算机视觉·扩散模型·视频编辑·视频生成·论文精读·不完美光流
程序猿小D6 小时前
【完整源码+数据集+部署教程】【零售和消费品&存货】价格标签检测系统源码&数据集全套:改进yolo11-RFAConv
前端·yolo·计算机视觉·目标跟踪·数据集·yolo11·价格标签检测系统源码
滑水滑成滑头6 小时前
**点云处理:发散创新,探索前沿技术**随着科技的飞速发展,点云处理技术在计算机视觉、自动驾驶、虚拟现实等领域的应用愈发广
java·python·科技·计算机视觉·自动驾驶
CoovallyAIHub7 小时前
超越“识别”:下一代机器视觉如何破解具身智能落地难题?
深度学习·算法·计算机视觉
Likeadust8 小时前
新版视频直播点播平台EasyDSS用视频破局,获客转化双提升
大数据·音视频
CoovallyAIHub8 小时前
全球OCR新标杆!百度0.9B小模型斩获四项SOTA,读懂复杂文档像人一样自然
深度学习·算法·计算机视觉