ComDesignProject/mydataset/videoTframe.py

54 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)