1

I used the below mentioned customer encoder to simultaneously record video as print a file containing time stamp values of each frame.

Here is the code:

#!/usr/bin/env python
# _*_ coding: utf-8 _*_

import io
import picamera
import socket
import time
import datetime as dt

WIDTH  = 640
HEIGHT = 480
FRAMERATE = 30
EXPOSURE_MODE = 'night'
BRIGHTNESS = 60
CONTRAST = 20
SHARPNESS = 25
AWB_MODE = 'off'
AWB_GAINS = 1.7

# An output (as far as picamera is concerned), is just a filename or an object
# which implements a write() method (and optionally the flush() and close()
# methods)
class MyOutput(object):
    def __init__(self, camera, video_filename, pts_filename):
        self.camera = camera
        self.videoOutputFile = io.open(video_filename, 'wb')
        self.timestampOutputFile = io.open(pts_filename, 'w')
        self.start_time = None

    def write(self, buf):
        self.videoOutputFile.write(buf)
        if self.camera.frame.complete and self.camera.frame.timestamp:
            if self.start_time == None:
                self.start = self.camera.frame.timestamp
        self.timestampOutputFile.write(u'%f, %s\n' % (((self.camera.frame.timestamp-self.start_time)/1000.0), dt.datetime.now().strfime("%H:%M:%S.%f")))

    def flush(self):
        self.videoOutputFile.flush()
        self.timestampOutputFile.flush()

    def close(self):
        self.videoOutputFile.close()
        self.timestampOutputFile.close()


runningTimeHours = raw_input('Enter the number of hours you want to record:')
runningTimeHours = float(runningTimeHours)

runningTimeMinutes = raw_input('Enter the number of minutes you want to record:')
runningTimeMinutes = float(runningTimeMinutes)

runningTimeSeconds = raw_input('Enter the number of seconds you want to record:')
runningTimeSeconds = float(runningTimeSeconds)

totalRunningTime = runningTimeHours*60*60 + runningTimeMinutes*60 + runningTimeSeconds


videoFileName = "output" + str(dt.datetime.now()) + ".h264"
timestampFileName = "timestamp" + str(dt.datetime.now()) + ".txt"

with picamera.PiCamera() as camera:
    camera.resolution = (WIDTH, HEIGHT)
    camera.framerate = FRAMERATE
    camera.brightness = BRIGHTNESS
    camera.contrast = CONTRAST
    camera.sharpness = SHARPNESS

    #warm-up time to camera to set its initial settings
    time.sleep(2)

    camera.exposure_mode = EXPOSURE_MODE
    camera.awb_mode = AWB_MODE
    camera.awb_gains = AWB_GAINS

    #time to let camera change parameters according to exposure and AWB
    time.sleep(2)

    camera.exposure_mode = 'off'    

    # Construct an instance of our custom output splitter with a filename  and a connected socket
    print 'Starting Recording'
    # Record video to the custom output (we need to specify the format as
    # the custom output doesn't pretend to be a file with a filename)
    camera.start_recording(MyOutput(camera, videoFileName, timestampFileName), format='h264')
    print 'Started Recording'
    camera.wait_recording(totalRunningTime)
    camera.stop_recording()
    print 'Recording Stopped'
    print 'Output File Closed'

and I am getting following errors:

Traceback (most recent call last):
  File "test_final.py", line 90, in <module>
    print 'Output File Closed'
  File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 976, in __exit__
    self.close()
  File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 955, in close
    self.stop_recording(splitter_port=port)
  File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1362, in stop_recording
    self.wait_recording(0, splitter_port)
  File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1333, in wait_recording
    encoder.wait(timeout)
  File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 853, in wait
    raise self.exception
TypeError: unsupported operand type(s) for -: 'long' and 'NoneType'

Kindly help me correct the issue please.

  • This question best fits Stack Overflow. – Gene Jan 23 '16 at 11:08
  • The exception is complaining that long and None can't be subtracted; the only place you're using subtraction is in your calculation of the time elapsed so I would suggest having a look around there. I can see one mistake in that you're setting self.start instead of self.start_time but even then there's no guarantee you'll get a valid timestamp on the first few frames (the first frame is usually a config frame which has timestamp None for example) – Dave Jones Jan 23 '16 at 11:35
  • Oh, and there's another error: you want strftime instead of strfime for formatting the system's timestamp – Dave Jones Jan 23 '16 at 11:36
  • Hey thanks Dave. I resolved the issue, kind of silly mistake from my side. – raj Jan 23 '16 at 12:13
  • Do you want to write your own answer to this then or should I close the question? – goldilocks Jan 23 '16 at 12:17
0

There were 2 main errors in the code, 1.) self.start_time == None which is the wrong way to compare. As a result of this, the start_time variable is not initialized and hence the error in subtraction. 2.) also for printing strftime was required rather than strfime. Here is the updated script.

#!/usr/bin/env python
# _*_ coding: utf-8 _*_

import io
import picamera
import socket
import time
import datetime as dt
import sys, getopt
from fractions import Fraction

WIDTH  = 640
HEIGHT = 480
FRAMERATE = 30
VIDEO_STABILIZATION = True
EXPOSURE_MODE = 'night'
BRIGHTNESS = 60
CONTRAST = 30
SHARPNESS = 30
AWB_MODE = 'off'
AWB_GAINS = 1.4

VIDEO_FILE_NAME = "cam1_output_" + str(dt.datetime.now()) + ".h264"
TIMESTAMP_FILE_NAME = "cam1_timestamp_" + str(dt.datetime.now()) + ".txt"
runningTimeHours, runningTimeMinutes, runningTimeSeconds = 0,0,0

# An output (as far as picamera is concerned), is just a filename or an object
# which implements a write() method (and optionally the flush() and close()
# methods)
class MyOutput(object):
    def __init__(self, camera, video_filename, pts_filename):
        self.camera = camera
        self.videoOutputFile = io.open(video_filename, 'wb')
        self.timestampOutputFile = io.open(pts_filename, 'w')
        self.start_time = None

    def write(self, buf):
        self.videoOutputFile.write(buf)
        if self.camera.frame.complete and self.camera.frame.timestamp:
            if self.start_time is None:
                self.start_time = self.camera.frame.timestamp
            self.timestampOutputFile.write(u'%f, %s\n' % (((self.camera.frame.timestamp-self.start_time)/1000.0), dt.datetime.now().strftime("%H:%M:%S.%f")))
        #print self.camera.awb_gains, self.camera.digital_gain, self.camera.analog_gain, self.camera.brightness, self.camera.contrast, self.camera.saturation , camera.exposure_speed 

    def flush(self):
        self.videoOutputFile.flush()
        self.timestampOutputFile.flush()

    def close(self):
        self.videoOutputFile.close()
        self.timestampOutputFile.close()

try:
    opts, args = getopt.getopt(sys.argv[1:], 'r:m:s:h', ['help',"hour=", "min=", "sec="])
except getopt.GetoptError, err: 
    print err
    sys.exit(2)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        print "Acquire_code.py -hr <hours> -m <mins> -s <secs>"
    elif opt in ('-r','--hour'):
        runningTimeHours = arg
    elif opt in ('-m','--min'):
        runningTimeMinutes = arg
    elif opt in ('-s','--sec'):
        runningTimeSeconds = arg

runningTimeHours = float(runningTimeHours)
runningTimeMinutes = float(runningTimeMinutes)
runningTimeSeconds = float(runningTimeSeconds)

totalRunningTime = runningTimeHours*60*60 + runningTimeMinutes*60 + runningTimeSeconds

#print totalRunningTime

try:
    with picamera.PiCamera() as camera:
        camera.resolution = (WIDTH, HEIGHT)
        camera.framerate = FRAMERATE
        camera.brightness = BRIGHTNESS
        camera.contrast = CONTRAST
        camera.sharpness = SHARPNESS
        camera.video_stabilization = VIDEO_STABILIZATION

        #warm-up time to camera to set its initial settings
        time.sleep(2)

        camera.exposure_mode = EXPOSURE_MODE
        camera.awb_mode = AWB_MODE
        camera.awb_gains = AWB_GAINS

        #time to let camera change parameters according to exposure and AWB
        time.sleep(2)

        camera.exposure_mode = 'off'
        camera.hflip = False
        camera.vflip = False

        camera.start_preview()
        # Construct an instance of our custom output splitter with a filename  and a connected socket
        print 'Starting Recording'
        # Record video to the custom output (we need to specify the format as
        # the custom output doesn't pretend to be a file with a filename)
        camera.start_recording(MyOutput(camera, VIDEO_FILE_NAME, TIMESTAMP_FILE_NAME), format='h264')
        print 'Started Recording'
        camera.wait_recording(totalRunningTime)
        camera.stop_recording()
        camera.stop_preview()
        print 'Recording Stopped'
        print 'Output File Closed'
except KeyboardInterrupt:
    print 'Closing Output File'
    sys.exit(2)
  • Whilst this code may work, it would be wise to include some explanation. – Darth Vader Oct 27 '16 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.