适用于单个或多个视频的抽帧,指定频率截取保存图像;采用多线程的处理方法、速度更快。
准备好待抽帧视频、建立图像保存文件夹:如下
import cv2
import os
import threading
def video2img(filename, fra):
cnt = 0
dnt = 0
cap = cv2.VideoCapture(video_path + os.sep + str(filename))
while True:
ret, image = cap.read()
if image is None:
break
if (cnt % fra) == 0:
cv2.imencode('.jpg', image)[1].tofile(img_path + os.sep + str(filename)[:-4] + '_' + str(dnt) + '.jpg')
dnt = dnt + 1
cnt = cnt + 1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
if __name__ == '__main__':
# 视频路径、图片保存路径
video_path = r"D:\road\video"
img_path = r"D:\road\img"
filelist = os.listdir(video_path)
# 设置抽帧频率;一般一秒为24帧,设置24即一秒截取一张图片
fra = 24
for filename in filelist:
threading.Thread(target=video2img, args=(filename, fra)).start()
图片按照对应视频名称命名,便于区分: