Reputation: 1
I got a video stream using RTSP protocol that I then send to my Python code using the OpenCV Video.Capture function. I just want to get 1 or 2 frames per second from that feed, process them and show the results of each one of them. Basically the output that I imagine would be a very low frame rate of the original feed with the processing I need. My question is, how do I only get a certain amount of frames to process and not all of them? Thank you!
Upvotes: 0
Views: 2140
Reputation: 11
You can use the function below to save and write x number of frames per second. The function takes 2 arguments - the video path and the number of frames you want to save per second. frames_per_second has a default value of 1 i.e prints a frame every second. You can change this parameter to increase or decrease number of frames saved per second. If you want to save less than a frame every second, you can input a value between 0 and 1 for frames_per_second e.g. 0.5 will print a frame every 2 seconds and 0.25 will print a frame every 4 seconds. And if you want all frames saved enter a value of -1 for frames_per_second.
import cv2
import math
import os
def video_to_images(video_path, frames_per_second=1):
cam = cv2.VideoCapture(video_path)
frame_list = []
frame_rate = cam.get(cv2.CAP_PROP_FPS) #video frame rate
# frame
current_frame = 0
# create directory if it does not exist
images_path = f'./data/images'
if not os.path.exists(images_path):
os.makedirs(images_path)
if frames_per_second > frame_rate or frames_per_second == -1:
frames_per_second = frame_rate
while(True):
# reading from frame
ret,frame = cam.read()
if ret:
# if video is still left continue creating images
file_name = f'{images_path}/frame' + str(current_frame) + '.jpg'
print ('Creating...' + file_name)
# print('frame rate', frame_rate)
if current_frame % (math.floor(frame_rate/frames_per_second)) == 0:
# adding frame to list
frame_list.append(frame)
# writing selected frames to images_path
cv2.imwrite(file_name, frame)
# increasing counter so that it will
# show how many frames are created
current_frame += 1
else:
break
# Release all space and windows once done
cam.release()
cv2.destroyAllWindows()
return frame_list
Upvotes: 1