Skip to content

Instantly share code, notes, and snippets.

@nickoala
Last active July 30, 2017 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickoala/0818146d24374c06b0a3dcd7f8a01ba7 to your computer and use it in GitHub Desktop.
Save nickoala/0818146d24374c06b0a3dcd7f8a01ba7 to your computer and use it in GitHub Desktop.
""" Raspberry Pi + GPS Car Camera
Achieved with three threads:
1. Main thread -
Start preview and recording.
2. GPS thread -
Read GPS location.
3. Annotate thread -
Put GPS location and datetime on image.
Refresh every one second to simulate a running clock.
Should be coupled with a cron job which deletes old video clips,
to prevent disk from filling up.
**Customize video size, preview dimension, and clip directory before trying.**
"""
import picamera
from datetime import datetime
import threading
import time
import os.path
import gps
video_size = (640, 480)
preview_dimension = (160, 0, 640, 480) # x, y, w, h
clip_directory = Full path to your clip directory, e.g. /home/pi/gpscam/clips
def record(camera):
def datetime_filename():
while 1:
yield (
os.path.join(
clip_directory,
datetime.now().strftime('%Y%m%d-%H%M') + '.h264'))
def seconds_to_cutoff():
cutoffs = [15, 30, 45, 60]
now = datetime.now()
for c in cutoffs:
if c <= now.minute:
continue
return c*60 - now.minute*60 - now.second
for filename in camera.record_sequence(datetime_filename()):
camera.wait_recording(seconds_to_cutoff())
latest_location = None
def gpsread():
global latest_location
session = gps.gps(mode=gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
for report in session:
if report['class'] == 'TPV':
if report['mode'] in [2,3]:
latest_location = (report['lat'], report['lon'])
else:
latest_location = None
# Separate annotation from GPS because I want to refresh the text
# once per second to give an illusion of a running clock.
def annotate(camera):
def compose_text(dt, location):
if location:
lat, lon = location
loctext = '%.4f%s %.4f%s' % (lat,
'N' if lat >= 0 else 'S',
lon,
'E' if lon >= 0 else 'W')
else:
loctext = '--lat-- --lon--'
return dt.strftime('%Y-%m-%d %H:%M:%S ') + loctext
global latest_location
camera.annotate_text_size = 24
while 1:
camera.annotate_text = compose_text(datetime.now(),
latest_location)
time.sleep(1)
camera = picamera.PiCamera(resolution=video_size, framerate=30)
gps_thread = threading.Thread(target=gpsread)
gps_thread.daemon = True
gps_thread.start()
annotate_thread = threading.Thread(target=annotate, args=[camera])
annotate_thread.daemon = True
annotate_thread.start()
camera.start_preview(fullscreen=False, window=preview_dimension)
record(camera)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment