pythonpicamera

Store 10 seconds of unencoded video buffer using Python


I am trying to save 10 seconds of buffered video using Python script, in particular '.rgb' format.

In order to do so, I have been using a PiCamera connected to a Raspberry Pi.

Based on the script below, if I choose to save the video using h264 format, I will be able to accomplish the desired goal successfully but if change the format from h264 to .rgb (targeted format), no outputs are generated.

Any thoughts what might be the issue here?

Thanks

Code snap:

import time
import io
import os 
import picamera
import datetime as dt
from PIL import Image
import cv2 

#obtain current time
def return_currentTime():
    return dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

#trigger event declaration
def motion_detected():
    while True:
        print ("Trigger event(y)?")
        trigger = input ()
        if trigger =="y":
            time = return_currentTime()
            print ("Buffering...")
            camera.wait_recording(5)     
            stream.copy_to(str(time)+'.rgb')            
           
        else: 
           camera.stop_recording()
           
           break
        
#countdown timer 
def countdown (t):
    while t:
        mins, secs = divmod (t,60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t-=1
    print('Buffer available!')
   

camera = picamera.PiCamera()

camera.resolution = (640, 480)

stream = picamera.PiCameraCircularIO(camera, seconds = 5)

#code will work using h264 as format
camera.start_recording (stream, format = 'rgb')
countdown(5)
motion_detected()

Solution

  • This question has to do with your stream format and how stream.copy_to() works.

    According to the docs for the function copy_to(output, size=None, seconds=None, first_frame=2), first_frame is a restriction on the first frame to be copied. This is set to sps_header by default, which is usually the first frame of an H264 stream.

    Since your stream format is RGB instead of H264, though, there are no sps_header's, and so copy_to cannot find an sps_header and copies nothing.

    To solve this, you have to allow any frame to be the first frame, not just sps_header's. This can be done by setting first_frame=None in your call, like copy_to(file, first_frame=None).