提取视频中切换镜头的帧(关键帧)
# coding=utf-8
import cv2
import matplotlib.pyplot as plt
import numpy as np
import copy
import os
def get_diff(frame_pre, frame):
return np.var((np.array(frame, dtype='int8') - np.array(frame_pre, dtype='int8')))
def main(video_source='test.mp4'):
try:
os.makedirs('frames') # 用于存放截图
except:
pass
capture = cv2.VideoCapture(video_source)
plt_list = list(np.zeros((20,)))
t_pause = 0.001
cnt = 0
frame_pre = 0
while True:
status, _frame = capture.read()
cnt += 1
plt_list.pop(0)
frame = copy.deepcopy(_frame)
frame = cv2.resize(frame, (400, 400))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('win1', frame)
if cv2.waitKey(1) & 0xFF == ord('q'): # 按q退出
break
diff = get_diff(frame_pre, frame) # 阈值:2500
if diff > 2500:
print('第{}帧,切换镜头'.format(cnt))
cv2.imwrite('frames/{}.jpg'.format(cnt), _frame)
frame_pre = frame
plt_list.append(diff)
plt.clf()
plt.plot(plt_list)
plt.ylim(-1000, 5000)
plt.pause(t_pause)
capture.release()
if __name__ == '__main__':
main()