Coding-视频转图片

按将一个视频切片成图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import cv2
import os
def extract_frames(video_path, output_folder):
"""
Extract frames from a video and save them to a specified folder.

Parameters:
video_path (str): The path to the video file.
output_folder (str): The path to the folder where frames will be saved.
"""
# Create the output folder if it does not exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)

# Open the video file
vidcap = cv2.VideoCapture(video_path)

# Check if video file was opened successfully
if not vidcap.isOpened():
print("Error opening video file")
return

# Read the video frame by frame
success, image = vidcap.read()
count = 0
while success:
# Save the frame as an image file
cv2.imwrite(os.path.join(output_folder, "frame{:d}.jpg".format(count)), image)
success, image = vidcap.read()
count += 1

print(f"Extracted {count} frames.")

video_path = 'nn.mp4'
video_outdir = 'video_data4'
extract_frames(video_path,video_outdir)