File size: 1,701 Bytes
342ea4d
 
 
e2d190f
342ea4d
 
 
 
 
 
 
 
 
 
e2d190f
 
 
342ea4d
 
 
 
 
 
 
 
 
e2d190f
 
 
 
 
342ea4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from deepface import DeepFace
import cv2
import os
import tempfile


def extract_frames(video_path, interval=30):
    """
    Extracts frames from a video at a specified interval.
    """
    # Open the video file
    cap = cv2.VideoCapture(video_path)
    frames = []
    count = 0
    
    # temp directory
    temp_dir = tempfile.gettempdir()

    # Loop through the video frames
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        #
        if count % interval == 0:
            frame_path = os.path.join(temp_dir, f"frame_{count}.jpg")
            
            success = cv2.imwrite(frame_path, frame)
            if success:
                frames.append(frame_path)
        count += 1

    # Release the video capture object
    cap.release()

    return frames


def verify_faces_in_video(video_path, reference_img, interval=30, threshold=0.7):
    """
    Verifies if faces in a video match a reference image.
    """
    results = []
    # Extract frames from the video
    frames = extract_frames(video_path, interval)

    # Loop through the frames
    for frame_path in frames:
        # Perform face verification
        try:
            # Perform face verification
            result = DeepFace.verify(
                img1_path=reference_img, img2_path=frame_path, enforce_detection=False
            )
            score = result["distance"]
            verified = result["verified"]
            results.append(
                {"frame": frame_path, "distance": round(score, 4), "verified": verified}
            )
        except Exception as e:
            results.append({"frame": frame_path, "error": str(e)})
    return results