My task today was to practice recording video with cv2.videoWriter(). Using code I pieced together from some of Adrian Rosenbrock’s tutorials and Dr. Mitchell’s stoplighttracker.py I created the following code:
#https://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/ #https://www.pyimagesearch.com/2016/02/22/writing-to-video-with-opencv/ # import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import time import datetime import cv2 from imutils.video import VideoStream # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (1920, 1088) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(1920, 1088)) #Define the codec today = time.strftime("%Y%m%d-%H%M%S") fps_out = 32 fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(today + ".avi", fourcc, fps_out, (1920, 1088)) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array # show the frame cv2.imshow("Frame", image) key = cv2.waitKey(1) & 0xFF #save the frame to a file out.write(image) # clear the stream in preparation for the next frame rawCapture.truncate(0) # if the `q` key was pressed, break from the loop if key == ord("q"): break
The camera.resolution, out resolution, and rawCapture have to have the same dimensions or the video won’t export.
I ran into an interesting phenomenon where the exported video is significantly shorter than the recorded video. I suspect this has something to do with a mismatch in frame rates. The video plays back at a much higher frame rate than I recorded.
fourcc = cv2.VideoWriter_fourcc(*’MJPG’)
fps_out = 10
out = cv2.VideoWriter(today + “.avi”, fourcc, fps_out, (1920, 1088))
I tried again.
Same results.
What if I exported a higher frame rate? (32 fps)
That’s actually faster.
What about trying XVID instead of MJPG?
Wow time flies when we’re having fun 🙂
I’ll have to do some more digging to figure out how to resolve this issue.