SHARE
TWEET

AcquistionwithTTL.py

rs99 Feb 2nd, 2017 (edited) 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #import the necessary modules
  2. import io
  3. import time
  4. import datetime as dt
  5. from picamera import PiCamera
  6. from threading import Thread, Event
  7. from queue import Queue, Empty
  8. import sys, getopt
  9. import argparse
  10. import RPi.GPIO as GPIO
  11.  
  12. #camera parameter setting
  13. WIDTH  = 640
  14. HEIGHT = 480
  15. FRAMERATE = 30
  16. VIDEO_STABILIZATION = True
  17. EXPOSURE_MODE = 'night'
  18. BRIGHTNESS = 55
  19. CONTRAST = 50
  20. SHARPNESS = 50
  21. SATURATION = 30
  22. AWB_MODE = 'off'
  23. AWB_GAINS = 1.4
  24.  
  25. #video, timestamps and ttl file name
  26. VIDEO_FILE_NAME = "cam4_output_" + str(dt.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + ".h264"
  27. TIMESTAMP_FILE_NAME = "cam4_timestamp_" + str(dt.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + ".csv"
  28. TTL_FILE_NAME = "cam4_ttl_" + str(dt.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + ".csv"
  29.  
  30. #running time variable intialization
  31. runningTimeHours, runningTimeMinutes, runningTimeSeconds = 0,0,0
  32.            
  33. #set raspberry pi board layout to BCM
  34. GPIO.setmode(GPIO.BCM)
  35. #pin number to receive TTL input
  36. pinTTL = 4
  37. #set the pin as input pin
  38. GPIO.setup(pinTTL, GPIO.IN)
  39. #add event detection script to GPIO pin
  40. GPIO.add_event_detect(pinTTL, GPIO.BOTH, bouncetime=900)
  41.        
  42. #video output thread to save video file
  43. class VideoOutput(Thread):
  44.     def __init__(self, filename):
  45.         super(VideoOutput, self).__init__()
  46.         self._output = io.open(filename, 'wb', buffering=0)
  47.         self._event = Event()
  48.         self._queue = Queue()
  49.         self.start()
  50.  
  51.     def write(self, buf):
  52.         self._queue.put(buf)
  53.         return len(buf)
  54.  
  55.     def run(self):
  56.         while not self._event.wait(0):
  57.             try:
  58.                 buf = self._queue.get(timeout=0.1)
  59.             except Empty:
  60.                 pass
  61.             else:
  62.                 self._output.write(buf)
  63.                 self._queue.task_done()
  64.  
  65.     def flush(self):
  66.         self._queue.join()
  67.         self._output.flush()
  68.  
  69.     def close(self):
  70.         self._event.set()
  71.         self.join()
  72.         self._output.close()
  73.  
  74.     @property
  75.     def name(self):
  76.         return self._output.name
  77.  
  78. #timestamp output object to save timestamps according to pi and TTL inputs received and write to file
  79. class TimestampOutput(object):
  80.     def __init__(self, camera, video_filename, timestamp_filename, ttl_filename):
  81.         self.camera = camera
  82.         self._video = VideoOutput(video_filename)
  83.         self._timestampFile = timestamp_filename
  84.         self._ttlFile = ttl_filename
  85.         self._timestamps = []
  86.         self._ttlTimestamps = []
  87.    
  88.     def ttlTimestampsWrite(self, input_pin):
  89.         try:
  90.             inputState = GPIO.input(input_pin)
  91.             self._ttlTimestamps.append((inputState, self.camera.frame.timestamp, self.camera.dateTime, self.camera.clockRealTime))
  92.         except Exception as e:
  93.             print(str(e))
  94.             pass
  95.  
  96.     def write(self, buf):
  97.         if self.camera.frame.complete and self.camera.frame.timestamp is not None:
  98.             self._timestamps.append((
  99.                 self.camera.frame.timestamp,
  100.                 self.camera.dateTime,
  101.                 self.camera.clockRealTime
  102.                 ))
  103.         return self._video.write(buf)
  104.  
  105.     def flush(self):
  106.         with io.open(self._timestampFile, 'w') as f:
  107.             f.write('GPU Times, time.time(), clock_realtime\n')
  108.             for entry in self._timestamps:
  109.                 f.write('%d,%f,%f\n' % entry)
  110.         with io.open(self._ttlFile, 'w') as f:
  111.             f.write('Input State, GPU Times, time.time(), clock_realtime\n')
  112.             for entry in self._ttlTimestamps:
  113.                 f.write('%f,%f,%f,%f\n' % entry)
  114.  
  115.     def close(self):
  116.         self._video.close()
  117.  
  118. parser = argparse.ArgumentParser()
  119. parser.add_argument("-hr", "--hours", type=int, help="number of hours to record")
  120. parser.add_argument("-m", "--minutes", type=int, help="number of minutes to record")
  121. parser.add_argument("-s", "--seconds", type=int, help="number of seconds to record")
  122. args = parser.parse_args()
  123.  
  124. runningTimeHours = float(args.hours)
  125. runningTimeMinutes = float(args.minutes)
  126. runningTimeSeconds = float(args.seconds)
  127.        
  128. totalRunningTime = runningTimeHours*60*60 + runningTimeMinutes*60 + runningTimeSeconds
  129.  
  130. with PiCamera(resolution=(WIDTH, HEIGHT), framerate=FRAMERATE) as camera:
  131.     camera.brightness = BRIGHTNESS
  132.     camera.contrast = CONTRAST
  133.     camera.sharpness = SHARPNESS
  134.     camera.video_stabilization = VIDEO_STABILIZATION
  135.     camera.hflip = False
  136.     camera.vflip = False
  137.  
  138.     #warm-up time to camera to set its initial settings
  139.     time.sleep(2)
  140.    
  141.     camera.exposure_mode = EXPOSURE_MODE
  142.     camera.awb_mode = AWB_MODE
  143.     camera.awb_gains = AWB_GAINS
  144.  
  145.     #time to let camera change parameters according to exposure and AWB
  146.     time.sleep(2)
  147.  
  148.     #switch off the exposure since the camera has been set now
  149.     camera.exposure_mode = 'off'
  150.  
  151.     output = TimestampOutput(camera, VIDEO_FILE_NAME, TIMESTAMP_FILE_NAME, TTL_FILE_NAME)
  152.     GPIO.add_event_callback(pinTTL, output.ttlTimestampsWrite)
  153.     try:
  154.         camera.start_preview()
  155.         # Construct an instance of our custom output splitter with a filename  and a connected socket
  156.         print('Starting Recording')
  157.         camera.start_recording(output, format='h264')
  158.         print('Started Recording')
  159.         camera.wait_recording(totalRunningTime)
  160.         camera.stop_recording()
  161.         camera.stop_preview()
  162.         print('Recording Stopped')
  163.     except KeyboardInterrupt:
  164.         print('Closing Output File')
  165.         sys.exit(2)
  166.     except:
  167.         output.close()
  168.         print('exception! output file closed')
  169.     finally:
  170.         output.close()
  171.         print('Output File Closed')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top