File size: 1,618 Bytes
80fcd93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Perceptual video hash: one 64-bit dHash per second, compared with time-shift search.

usage: python3 vhash.py a.mp4 b.mp4 [c.mp4 ...]
Prints a distance matrix (average differing bits out of 64, lower = more alike).
"""
import subprocess, sys
import numpy as np

def dhashes(path, step=1.0):
    """dHash of one frame per `step` seconds (9x8 gray, compare neighbours)."""
    cmd = ["ffmpeg", "-v", "error", "-i", path, "-vf",
           f"fps=1/{step}:start_time=0.5,scale=9:8:flags=area,format=gray",
           "-f", "rawvideo", "-"]
    raw = subprocess.run(cmd, capture_output=True, check=True).stdout
    px = np.frombuffer(raw, np.uint8).reshape(-1, 8, 9).astype(np.int16)
    return (px[:, :, 1:] > px[:, :, :-1]).reshape(len(px), 64)

def distance(a, b, max_shift=3):
    """Best mean Hamming distance over whole-second shifts of b against a."""
    best = (64.0, 0)
    for s in range(-max_shift, max_shift + 1):
        x = a[max(0, s):]
        y = b[max(0, -s):]
        n = min(len(x), len(y))
        if n < 4:
            continue
        d = float(np.mean(np.sum(x[:n] != y[:n], axis=1)))
        best = min(best, (d, s))
    return best

if __name__ == "__main__":
    files = sys.argv[1:]
    H = [dhashes(f) for f in files]
    names = [f.rsplit("/", 1)[-1][:14] for f in files]
    print(" " * 16 + "".join(f"{n[:9]:>11}" for n in names))
    for i, a in enumerate(H):
        cells = []
        for j, b in enumerate(H):
            d, s = distance(a, b)
            cells.append(f"{d:5.1f}({s:+d})")
        print(f"{names[i]:<16}" + "".join(f"{c:>11}" for c in cells))