I have a series of videos and I want to save frames from them as images. This is my code:
JavaScript
x
26
26
1
import os, cv2
2
3
current_dir = os.getcwd()
4
training_videos = '../../Videos/training_videos/'
5
6
if not os.path.exists(current_dir + '/training_images/'):
7
os.mkdir(current_dir + '/training_images/')
8
9
for i in os.listdir(training_videos):
10
11
video = cv2.VideoCapture('../../Videos/training_videos/' + i)
12
13
currentFrame = 0
14
15
while (True):
16
# Capture frame-by-frame
17
ret, frame = video.read()
18
19
# Saves image of the current frame in jpg file
20
name = current_dir + '/training_images/frame' + str(currentFrame) + '.png'
21
print('Creating...' + name)
22
cv2.imwrite(name, frame)
23
24
# To stop duplicate images
25
currentFrame += 1
26
This code works but unfortunately, it takes a frame at every millisecond. This is not something I want. Instead, I want to save a frame at every 5 or 10 seconds. I thought about adding a time delay but that wouldn’t really work because the videos are not live streams so after 5 seconds, it’ll just take the screenshot right after the previous millisecond.
Advertisement
Answer
There’s likely an more efficient way, but you can do this by using the frame rate of the video and then processing the image every FRAME_RATE * 5
frames.
Your code would look something like this (let me know if this doesn’t work as I haven’t ran this on my PC):
JavaScript
1
30
30
1
import os, cv2
2
3
current_dir = os.getcwd()
4
training_videos = '../../Videos/training_videos/'
5
6
if not os.path.exists(current_dir + '/training_images/'):
7
os.mkdir(current_dir + '/training_images/')
8
9
for i in os.listdir(training_videos):
10
11
video = cv2.VideoCapture('../../Videos/training_videos/' + i)
12
fps = video.get(cv2.CAP_PROP_FPS)
13
14
currentFrame = 0
15
16
while video.isOpened():
17
# Capture frame-by-frame
18
ret, frame = video.read()
19
20
if (video):
21
# Write current frame
22
name = current_dir + '/training_images/frame' + str(currentFrame) + '.png'
23
print('Creating...' + name)
24
cv2.imwrite(name, frame)
25
26
currentFrame += fps * 5
27
# Skip to next 5 seconds
28
video.set(cv2.CAP_PROP_POS_FRAMES, currentFrame)
29
30