52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
|
import cv2
|
||
|
import os
|
||
|
|
||
|
|
||
|
def extract_frames(video_path, output_dir, interval=0.5,output_name='frame'):
|
||
|
# 打开视频文件
|
||
|
cap = cv2.VideoCapture(video_path)
|
||
|
|
||
|
if not cap.isOpened():
|
||
|
print(f"无法打开视频文件: {video_path}")
|
||
|
return
|
||
|
|
||
|
# 获取视频帧率和总时长
|
||
|
fps = cap.get(cv2.CAP_PROP_FPS)
|
||
|
frame_interval = int(fps * interval) # 每隔多少帧保存一帧
|
||
|
print(fps)
|
||
|
# 创建输出目录
|
||
|
os.makedirs(output_dir, exist_ok=True)
|
||
|
|
||
|
frame_count = 0
|
||
|
saved_count = 0
|
||
|
|
||
|
while True:
|
||
|
ret, frame = cap.read()
|
||
|
if not ret:
|
||
|
break
|
||
|
|
||
|
# 如果当前帧是需要保存的帧
|
||
|
if frame_count % frame_interval == 0:
|
||
|
output_image_path = os.path.join(output_dir, f"{output_name}_{saved_count}.jpg")
|
||
|
cv2.imwrite(output_image_path, frame)
|
||
|
print(f"保存帧到: {output_image_path}")
|
||
|
saved_count += 1
|
||
|
|
||
|
frame_count += 1
|
||
|
|
||
|
# 释放视频对象
|
||
|
cap.release()
|
||
|
print(f"共保存了 {saved_count} 帧.")
|
||
|
|
||
|
video_dir=r'C:\Users\10561\Desktop\bcar红绿灯\1'
|
||
|
output_directory = r"C:\Users\10561\Desktop\frames" # 替换为你希望保存的目录路径
|
||
|
|
||
|
for file in os.listdir(video_dir):
|
||
|
if file.endswith('.mp4'):
|
||
|
video_file=os.path.join(video_dir,file)
|
||
|
extract_frames(video_file, output_directory, interval=0.4,output_name=file.split('.')[0])
|
||
|
|
||
|
# 示例调用
|
||
|
# video_file = r"C:\Users\10561\Desktop\7.mp4" # 替换为你的视频文件路径
|
||
|
# extract_frames(video_file, output_directory, interval=0.5)
|