视频按帧截取 python程序
- 代码注释很清晰,请自行阅读,
- 参考部分网络资源,由于较难追溯,不记出处。
import cv2 as cv
import os
# 视频路径
video_path = "/home/username/Videos/file.mp4"
cap = cv.VideoCapture(video_path)
frameRate = 5 # 帧数截取间隔
# 保存路径
aim_path = "./capture_image/"
if not os.path.exists(aim_path):
os.mkdir(aim_path)
fCount = 0 # 计数器
while (True):
ret, frame = cap.read()
fCount += 1
if ret:
if (fCount % frameRate == 0):
# 这里就可以做一些操作了:显示截取的帧图片、保存截取帧到本地
cv.imshow("frame", frame)
# 延时ms,默认值为0,此时需要按键继续。
cv.waitKey(100)
key = cv.waitKey()
# n键 下一张
if key == ord("n"):
cv.destroyAllWindows()
continue
# Esc 退出
elif key == 27:
cv.destroyAllWindows()
break
# space 保存当前帧
elif key == 32:
cv.destroyAllWindows()
print("开始截取视频第:" + str(fCount) + " 帧")
cv.imwrite(aim_path + str("210925%05d" %
fCount) + '.jpg', frame)
print("Save this frame!")
# other键 下一张并提示
else:
print("Retype please!")
cv.destroyAllWindows()
else:
print("已无帧可存。")
break
cap.release()