从视频中提取关键帧,以便删除重复的帧

时间:2021-01-03 16:37:58

标签: python-3.x image-processing opencv-python

这是用于提取关键帧以删除重复帧的代码。我面临的问题是没有生成帧,因为没有计算 variance 变量,因此发生了错误。

import cv2
import os
from matplotlib import pyplot as plt
import numpy as np
cap = cv2.VideoCapture("s06.mp4")
frame_list = []
try:
    if not os.path.exists('data'):
        os.makedirs('data')
except OSError:
    print("Error cant make directories")

    
cframe = 0
while(True):
        if os.path.exists('data'):
                break

        
        ret, frame= cap.read()
        name = './data/' + str(cframe) + '.jpg'
        print("creating" +name)
        cv2.imwrite(name,frame)

        frame_list.append(frame)
        cframe += 1
 
        if not ret:
                break


images = {}
index = {}


import glob

for imagePath in glob.glob('./data/*.jpg'):
    filename = imagePath[imagePath.rfind("/") + 1:]
                  
    image = cv2.imread(imagePath,1)
    images[filename] = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    hist = cv2.calcHist([image],[0,1,2],None,[8,8,8],[0,256,0,256,0,256])
    hist = cv2.normalize(hist,None).flatten()
    index[filename] = hist


OPENCV_METHODS = (
    (cv2.HISTCMP_CORREL ),
    (cv2.HISTCMP_CHISQR),
    (cv2.HISTCMP_INTERSECT), 
    (cv2.HISTCMP_BHATTACHARYYA))
 

for method in OPENCV_METHODS:

    
    results = {}
    reverse = False
 
    
    
    if method in (cv2.HISTCMP_CORREL, cv2.HISTCMP_INTERSECT ):
        reverse = True




for (k, hist) in index.items():
        
        d = cv2.compareHist(index[k], hist, cv2.HISTCMP_INTERSECT)
        results[k] = d
        print(d)

        
    
for (k,hist) in index.items():
    mean__ = np.mean(index[k], dtype=np.float64)

    

for (k,hist) in index.items():
    variance = np.var(index[k], dtype=np.float64)
        

print("variance", variance)
        
standard_deviation = np.sqrt(variance)
th = mean__ + standard_deviation + 3
print("threshold value", th)

try:
    if not os.path.exists('keyframes'):
        os.makedirs('keyframes')
except OSError:
    print("Error cant make directories")


cframe1=0
for (k,hist) in index.items():
        d = cv2.compareHist(index[k], hist, cv2.HISTCMP_INTERSECT)
        ret, keyframe = cap.read()

        if not ret:
                break
        
        if (d > th):
                name = './keyframes/' + str(cframe1) + '.jpg'
                print("creating" +name)
                cv2.imwrite(name, keyframe )
                cframe1+=1



Traceback (most recent call last):
  File "C:\Users\User\Desktop\FYP\New folder (2)\test.py", line 87, in <module>
    print(variance)
NameError: name 'variance' is not defined

请告诉我没有制作框架的错误。

代码基于此算法。

算法 选择关键帧的方法之一是利用连续帧的直方图差异。

  • 一一提取帧。2个连续帧之间的直方图差异。
  • 计算绝对差的均值和标准差
  • 计算阈值(t= σadh + µadh)
  • 如果它大于 T,则与 T 进行比较。选择它作为关键帧。

继续直到结束。 其中 µadh= 均值绝对差 并且,σadh=绝对差的标准差。

  • 保真度度量:对保留镜头全局内容的方法的度量。
  • 压缩比:研究镜头内容的压缩。

0 个答案:

没有答案