我正在尝试编写一个openCV程序,我将视频分解为帧并逐个比较两个帧如果两个帧相同我拒绝帧,否则将帧附加到输出文件。
我怎样才能实现它?
OpenCV 2.4.13 Python 2.7
答案 0 :(得分:3)
以下示例从连接到系统的第一台摄像机捕获帧,将每帧与前一帧进行比较,如果不同,则将帧添加到文件中。如果您静止在相机前面,如果从控制台终端窗口运行程序,则可能会看到诊断“无更改”消息。
有多种方法可以衡量一帧与另一帧的不同。为简单起见,我们使用了新帧和前一帧之间的逐像素平均差异,与阈值进行比较。
请注意,openCV读取函数将帧返回为numpy数组。
import numpy as np
import cv2
interval = 100
fps = 1000./interval
camnum = 0
outfilename = 'temp.avi'
threshold=100.
cap = cv2.VideoCapture(camnum)
ret, frame = cap.read()
height, width, nchannels = frame.shape
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter( outfilename,fourcc, fps, (width,height))
while(True):
# previous frame
frame0 = frame
# new frame
ret, frame = cap.read()
if not ret:
break
# how different is it?
if np.sum( np.absolute(frame-frame0) )/np.size(frame) > threshold:
out.write( frame )
else:
print( 'no change' )
# show it
cv2.imshow('Type "q" to close',frame)
# check for keystroke
key = cv2.waitKey(interval) & 0xFF
# exit if so-commanded
if key == ord('q'):
print('received key q' )
break
# When everything done, release the capture
cap.release()
out.release()
print('VideoDemo - exit' )