DHASH感知算法计算视频相邻帧的相似度

一个朋友想用python来读取视频帧,根据帧和帧之间相似度判断剪辑痕迹;但是最后发现并没什么用......

原理就是遍历地读取图像相邻帧,将图像相邻帧前处理后,缩小什么的,计算d_hash,然后计算其汉明距离,然后把汉明距离变成相似度,比较相似度,如果相似度低于阈值,就标记时间什么的

不过我一想,欸!好像可以用来解GIF隐写

我就把代码放这里了

1.处理视频版本的

python 复制代码
import cv2
import numpy as np
from PIL import Image

# Constants
VIDEO_FILE = "faker.mp4"
FRAME_PREFIX = "frame"
FAIL_THRESHOLD = 0.77

def d_hash(image):
    """Calculate the difference hash for the given image."""
    hash_bits = []
    for i in range(8):
        for j in range(8):
            hash_bits.append(1 if image[i, j] > image[i, j + 1] else 0)
    return hash_bits

def hamming_distance(hash1, hash2):
    """Calculate the Hamming distance between two hashes."""
    return sum(1 for x, y in zip(hash1, hash2) if x != y)

def process_frame(frame):
    """Process frame to convert it to a format suitable for hash computation."""
    return np.array(Image.fromarray(frame).resize((9, 8), Image.LANCZOS).convert('L'), 'f')

def main():
    video = cv2.VideoCapture(VIDEO_FILE)
    edit_detected = False

    while True:
        # Read two consecutive frames from the video
        success, frame0 = video.read()
        success1, frame1 = video.read()

        if not success or not success1:
            break

        # Process frames
        frame0_processed = process_frame(frame0)
        frame1_processed = process_frame(frame1)

        # Calculate hashes and distance
        hash0 = d_hash(frame0_processed)
        hash1 = d_hash(frame1_processed)
        distance = hamming_distance(hash0, hash1)
        similarity = 1.0 - distance / 64.0

        # Check similarity against the threshold
        if similarity < FAIL_THRESHOLD:
            msec = video.get(cv2.CAP_PROP_POS_MSEC)
            minute, second = divmod(msec // 1000, 60)
            print(f"{int(minute)} minute {int(second)} second detected with similarity {similarity}")
            edit_detected = True

    if not edit_detected:
        print("No edit detected.")

if __name__ == "__main__":
    main()

2.处理GIF版本的

处理GIF的时候如果遇到相似度过低的帧,就标记出来,而不是时间

python 复制代码
from PIL import Image, ImageSequence
import numpy as np

# Constants
GIF_FILE = "aaa.gif"
FRAME_PREFIX = "frame"
FAIL_THRESHOLD = 0.77

def d_hash(image):
    """Calculate the difference hash for the given image."""
    hash_bits = []
    for i in range(8):
        for j in range(8):
            hash_bits.append(1 if image[i, j] > image[i, j + 1] else 0)
    return hash_bits

def hamming_distance(hash1, hash2):
    """Calculate the Hamming distance between two hashes."""
    return sum(1 for x, y in zip(hash1, hash2) if x != y)

def process_frame(frame):
    """Process frame to convert it to a format suitable for hash computation."""
    return np.array(frame.resize((9, 8), Image.LANCZOS).convert('L'), 'f')

def main():
    gif = Image.open(GIF_FILE)
    frames = [frame.copy() for frame in ImageSequence.Iterator(gif)]
    edit_detected = False
    previous_hash = None

    for index, frame in enumerate(frames):
        # Process frame
        frame_processed = process_frame(frame)

        # Calculate hash
        current_hash = d_hash(frame_processed)

        if previous_hash is not None:
            # Calculate distance and similarity
            distance = hamming_distance(previous_hash, current_hash)
            similarity = 1.0 - distance / 64.0

            # Check similarity against the threshold
            if similarity < FAIL_THRESHOLD:
                print(f"Frame {index} detected with similarity {similarity}")
                edit_detected = True
        
        previous_hash = current_hash

    if not edit_detected:
        print("No edit detected.")

if __name__ == "__main__":
    main()

FAIL_THRESHOLD那里可以调节灵敏度,越高越容易筛选帧对

不过话说回来,好像还是很鸡肋......算了......写都写了

兴许以后有用呢。

相关推荐
烟雨江南78511 小时前
200路并发语音识别系统实践:CPU、GPU与国产昇腾三种部署方案怎么选?
人工智能·websocket·音视频·语音识别·ai客服
视频技术分享12 小时前
视频会议系统技术全解:底层架构、选型标准与实战优化
架构·音视频
林墨聊AIGC13 小时前
AI视频怎么做跳舞的动作效果:从入门到精通的舞蹈动画制作指南
大数据·人工智能·自动化·aigc·音视频
小鱼爱吃草灬灬17 小时前
实时面试辅助排查清单:音频来源、问题输入与上下文
面试·职场和发展·音视频
可乐鸡翅yeah_17 小时前
HLS 自动化拨测与手动调试分工,流媒体线上监控体系建设实践
运维·自动化·测试用例·音视频·媒体·m3u8·音视频在线播放
欧特克_Glodon18 小时前
OpenCV计算机视觉开发入门与实践<三十五>:开发视频播放器
c++·opencv·计算机视觉·音视频
2301_7681034920 小时前
AI视频创作Agent实战05:Wan场景融合与VideoRetalk口型驱动
人工智能·音视频
淼澄研学20 小时前
Sonos空间音频技术解析与Python本地API控制实操
开发语言·python·音视频
可乐鸡翅yeah_20 小时前
M3U8测试流使用指南,流媒体开发自测与环境校验标准化方案
网络·ffmpeg·音视频·m3u8·m3u8在线·音视频在线播放
TechVoyager_824621 小时前
不止是HDMI发射器:IT6622的eARC音频回传功能详解
音视频·片载 mcu·earc 音频回传·hdmi 发射器·影音芯片·hdmi1.4 发射·it6622