[英]Extracting keyframes | Python | Opencv
我目前正在從視頻中提取關鍵幀。
代碼 :
while success:
success, currentFrame = vidcap.read()
isDuplicate = False
limit = count if count <= 10 else (count - 10)
for img in xrange(limit, count):
previusFrame = cv2.imread("%sframe-%d.png" % (outputDir, img))
try:
difference = cv2.subtract(currentFrame, previusFrame)
except:
pass
這給了我大量的幀。 預期輸出:計算幀之間的像素差異,然后將其與閾值進行比較並存儲唯一的關鍵幀。
第一次處理視頻。 請指導如何繼續實現預期的輸出
這是一個使用 ffprobe 和 OpenCV 提取 I 幀的腳本:
import os
import cv2
import subprocess
filename = '/home/andriy/Downloads/video.mp4'
def get_frame_types(video_fn):
command = 'ffprobe -v error -show_entries frame=pict_type -of default=noprint_wrappers=1'.split()
out = subprocess.check_output(command + [video_fn]).decode()
frame_types = out.replace('pict_type=','').split()
return zip(range(len(frame_types)), frame_types)
def save_i_keyframes(video_fn):
frame_types = get_frame_types(video_fn)
i_frames = [x[0] for x in frame_types if x[1]=='I']
if i_frames:
basename = os.path.splitext(os.path.basename(video_fn))[0]
cap = cv2.VideoCapture(video_fn)
for frame_no in i_frames:
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
ret, frame = cap.read()
outname = basename+'_i_frame_'+str(frame_no)+'.jpg'
cv2.imwrite(outname, frame)
print ('Saved: '+outname)
cap.release()
else:
print ('No I-frames in '+video_fn)
if __name__ == '__main__':
save_i_keyframes(filename)
如果需要提取 P 幀,可以將'I'
更改為'P'
。
您可以使用以下代碼片段,它遍歷所有幀並檢查幀之間的差異,如下所示:
import cv2
import numpy as np
video_path = "/Users/anmoluppal/Downloads/SampleVideo_1280x720_1mb.mp4"
p_frame_thresh = 300000 # You may need to adjust this threshold
cap = cv2.VideoCapture(video_path)
# Read the first frame.
ret, prev_frame = cap.read()
while ret:
ret, curr_frame = cap.read()
if ret:
diff = cv2.absdiff(curr_frame, prev_frame)
non_zero_count = np.count_nonzero(diff)
if non_zero_count > p_frame_thresh:
print "Got P-Frame"
prev_frame = curr_frame
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.