I am trying to do video recording on Jetson Nano. I found that when the cv2.VideoWriter
using write()
the program becomes slow. How can I speed up the cv2.VideoWriter
? Maybe use Gstreamer
or GPU
or nvidia-component
can speed up the FPS.
My Code:
import os
import time
import cv2
width = 2560
height = 1440
framerate = 30
video_path = 'fps_test.mp4'
gs_pipeline = f"v4l2src device=/dev/video0 io-mode=2 " \
f"! image/jpeg, width={width}, height={height}, framerate={framerate}/1, format=MJPG " \
f"! nvv4l2decoder mjpeg=1 " \
f"! nvvidconv flip-method=4 " \
f"! video/x-raw, format=BGRx " \
f"! videoconvert " \
f"! video/x-raw, format=BGR " \
f"! appsink drop=1"
gs_pipeline = gs_pipeline
print(f"gst-launch-1.0 {gs_pipeline}\n")
v_cap = v_writer = None
def main():
global v_cap, v_writer
codec = cv2.VideoWriter_fourcc(*'mp4v')
v_writer = cv2.VideoWriter(video_path, codec, 20, (width, height))
v_cap = cv2.VideoCapture(gs_pipeline, cv2.CAP_GSTREAMER)
prev_frame_fetched_time = 0
while v_cap.isOpened():
ret_val, frame = v_cap.read()
if not ret_val:
break
v_writer.write(frame)
curr_frame_fetched_time = time.time()
curr_fps = 1 / (curr_frame_fetched_time - prev_frame_fetched_time)
prev_frame_fetched_time = curr_frame_fetched_time
print(f"FPS = {curr_fps:.3f}")
v_cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
pass
finally:
v_cap.release()
cv2.destroyAllWindows()
if os.path.exists(video_path):
os.remove(video_path)
Console:
FPS = 0.000
FPS = 2.438
FPS = 3.606
FPS = 2.805
FPS = 2.741
FPS = 3.265
FPS = 3.603
FPS = 3.524
FPS = 3.290