python+opencv裁剪视频

python有极其方便的脚本特性,用来做一些脚本工作非常合适。对于经常用到的小脚本儿,用个博文记下来,以免下次又重新写  ~ -_-。

环境:python2/3 + opencv 3.1 


功能:输入一个长视频,我想用帧序号的方法截取其中的一小段,只需明确起始帧结束帧即可

脚本如下:

import cv2

INPUT_FILE = 't1.avi'
OUTPUT_FILE = 'clip1.avi'
start_frame = 10
end_frame = 50

reader = cv2.VideoCapture(INPUT_FILE)
width = int(reader.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(reader.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter(OUTPUT_FILE, 
              cv2.VideoWriter_fourcc('I', '4', '2', '0'),
              30, # fps
              (width, height)) # resolution

print(reader.isOpened())
have_more_frame = True
c = 0
while have_more_frame:
    have_more_frame, frame = reader.read()
    c += 1
    if c>= start_frame and c<= end_frame:
        cv2.waitKey(1)
        writer.write(frame)
        print(str(c) + ' is ok')
    if c>end_frame:
        print('completely!')
        break


writer.release()
reader.release()
cv2.destroyAllWindows()

 

你可能感兴趣的:(Computer,Vision,python,opencv,python,script,video)