54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
import os
|
||
import cv2
|
||
|
||
|
||
def video2frame(video_src_path = "video/", frame_save_path = "images/img/", frame_width = 1920, frame_height = 1080,
|
||
interval = 1):
|
||
"""
|
||
将视频按固定间隔读取写入图片
|
||
:param video_src_path: 视频存放路径
|
||
:param frame_save_path: 保存路径
|
||
:param frame_width: 保存帧宽
|
||
:param frame_height: 保存帧高
|
||
:param interval: 保存帧间隔,由于video文件夹视频已经抽过帧了,此处该参数设置为1
|
||
"""
|
||
videos = os.listdir(video_src_path)
|
||
|
||
for each_video in videos:
|
||
print("正在读取视频:", each_video)
|
||
|
||
each_video_save_full_path = os.path.join(frame_save_path, each_video.split(".")[0])
|
||
if not os.path.exists(each_video_save_full_path):
|
||
os.makedirs(each_video_save_full_path)
|
||
|
||
frame_index = 0
|
||
frame_count = 0
|
||
cap = cv2.VideoCapture(os.path.join(video_src_path, each_video))
|
||
|
||
if not cap.isOpened():
|
||
print("读取失败!")
|
||
|
||
while cap.isOpened():
|
||
ret, frame = cap.read()
|
||
if ret:
|
||
print("---> 正在读取第{:d}帧".format(frame_index))
|
||
|
||
if frame_index % interval == 0:
|
||
save_img = cv2.resize(frame, (frame_width, frame_height), interpolation = cv2.INTER_AREA)
|
||
save_img_name = os.path.join(each_video_save_full_path, str(frame_count).zfill(3) + ".jpg")
|
||
cv2.imwrite(save_img_name, save_img)
|
||
frame_count += 1
|
||
frame_index += 1
|
||
else:
|
||
break
|
||
cap.release()
|
||
|
||
|
||
if __name__ == '__main__':
|
||
videos_src_path = "video/"
|
||
frames_save_path = "images/img/"
|
||
width = 1920
|
||
height = 1080
|
||
time_interval = 1
|
||
video2frame(videos_src_path, frames_save_path, width, height, time_interval)
|