forked from dofl/PiCam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpicam.py
256 lines (194 loc) · 8.75 KB
/
picam.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#! /usr/bin/env python
import os
import picamera
import picamera.array
import time
import datetime
import time
import logging
import numpy as np
import RPi.GPIO as GPIO
from astral import Astral
from fractions import Fraction
camera = picamera.PiCamera()
# ----------------------- Settings ------------------------------------------------------------
config = {}
file_name = "picam.cfg"
config_file= open(file_name)
for line in config_file:
line = line.strip()
if line and line[0] is not "#" and line[-1] is not "=":
var,val = line.rsplit("=",1)
config[var.strip()] = val.strip()
# Image file save loction? No tailing /
# Leave at /mnt/picam_ramdisk when using the storageController.sh
imageFileLocation = config["RAMDISK"]
imageFileLocationOffline = config["OFFLINE"] # Set to None (without '') if not used
# Camera
camera.resolution = (config["CAM_RESOLUTION_X"], config["CAM_RESOLUTION_Y"])
camera.hflip = config["CAM_HFLIP"]
camera.vflip = config["CAM_VFLIP"]
camera.rotation = config["CAM_ROTATION"]
imageQuality = config["IMAGE_QUALITY"] # jpg image quality 0-100 (200KB-1.5MB per image)
# Astral location for sunset and sunrise/ Find your nearest city here: http://pythonhosted.org/astral/#cities
astral_location = config["ASTRAL_LOCATION"]
astralIsDay = config["ASTRAL_IS_DAY"]
# LED settings
CamLed = config["CAM_LED"]
ledTurnOnTime = config["LED_TURN_ON_TIME"]
ledTurnOffTime = config["LED_TURN_OFF_TIME"]
# Motion detection
motionScoreDay = config["MOTION_SCORE_DAY"]
motionScoreNight = config["MOTION_SCORE_NIGHT"]
imagesToShootAtMotion = config["IMAGES_TO_SHOOT_AT_MOTION"]
#-----------------------------------------------------------------------------------------------
# System Initialisation
# Astral
astralLastUpdateTime = datetime.datetime.now() + datetime.timedelta(-1)
astralSunPosition = None # dictionary with sunrise and sunset
# logging
logging.basicConfig(filename='picam.log', level=logging.INFO, format='%(asctime)s %(message)s')
LOG = logging.getLogger("capture_motion")
# Initiate camera
motionDetected = False
MotionLastStillCaptureTime = datetime.datetime.now()
# initialise camera LED
GPIO.setmode(GPIO.BCM)
GPIO.setup(CamLed, GPIO.OUT, initial=False)
isCameraLedOn = False
#-----------------------------------------------------------------------------------------------
# Get available disk space
def freeSpaceAvailable():
freeSpaceAvailable = True
try:
st = os.statvfs(imageFileLocation + "/")
diskSpaceFree = st.f_bavail * st.f_frsize
diskSpaceRequired = 2 * 1024 * 1024 #2 MB
if diskSpaceFree < diskSpaceRequired:
freeSpaceAvailable = False
except Exception:
LOG.info('Exception', exc_info=True)
return freeSpaceAvailable
#-----------------------------------------------------------------------------------------------
def UpdateAstral():
global astralLastUpdateTime, astralSunPosition, astralIsDay
# Sunrise and Sunset times updates every 24h
if (astralLastUpdateTime < (datetime.datetime.now() - datetime.timedelta(hours=24))):
LOG.info("Updating astral because of 24h difference: " + str(datetime.datetime.now() - astralLastUpdateTime))
astralLastUpdateTime = datetime.datetime.now()
astralSunPosition = Astral()[astral_location].sun(None, local=True)
LOG.info("Astral updated to sunrise " + \
astralSunPosition['sunrise'].time().strftime('%H:%M') + \
" and sunset " + astralSunPosition['sunset'].time().strftime('%H:%M'))
# Switch between day and night by Astral sunrise and sunset
if (time.strftime("%H:%M") == astralSunPosition['sunrise'].time().strftime('%H:%M')) and astralIsDay == False:
astralIsDay = True
LOG.info("Astral: Uprise of the light")
if (time.strftime("%H:%M") == astralSunPosition['sunset'].time().strftime('%H:%M')) and astralIsDay == True:
astralIsDay = False
LOG.info("Astral: Darkness cometh")
#-----------------------------------------------------------------------------------------------
def UpdateLED():
global isCameraLedOn
if (time.strftime("%H:%M") == ledTurnOnTime) and isCameraLedOn == False:
LOG.info("LED: Turned on")
GPIO.output(CamLed, True)
isCameraLedOn = True
if (time.strftime("%H:%M") == ledTurnOffTime) and isCameraLedOn == True:
LOG.info("LED: Turned off")
GPIO.output(CamLed, False)
isCameraLedOn = False
#-----------------------------------------------------------------------------------------------
# Day motion detection uses the camera to constantly record and analyse every frame for motion.
# This is quicker then shooting seperate images and comparing.
class DetectMotion(picamera.array.PiMotionAnalysis):
def analyse(self, a):
global motionDetected, MotionLastStillCaptureTime, motionScoreDay, motionScoreNight, astralIsDay
if astralIsDay:
motionScore = motionScoreDay
else:
motionScore = motionScoreNight
if datetime.datetime.now() > MotionLastStillCaptureTime + \
datetime.timedelta(seconds=1):
a = np.sqrt(
np.square(a['x'].astype(np.float)) +
np.square(a['y'].astype(np.float))
).clip(0, 255).astype(np.uint8)
if (a > 60).sum() > motionScore:
motionDetected = True
#-----------------------------------------------------------------------------------------------
def FilenameGenerator():
filename = None
if freeSpaceAvailable():
filename = imageFileLocation + "/" + datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
else:
if imageFileLocation == "None":
LOG.info('No space left on disk. Will not save image')
else:
filename = imageFileLocationOffline + "/" + datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
return filename
#-----------------------------------------------------------------------------------------------
def CameraRecordingSettings():
camera.framerate = 10
camera.exposure_mode = 'auto'
camera.awb_mode = 'auto'
camera.iso = 0
#-----------------------------------------------------------------------------------------------
def CameraDaySettings():
camera.exposure_mode = 'auto'
camera.awb_mode = 'auto'
camera.iso = 0
#-----------------------------------------------------------------------------------------------
def CameraNightSettings():
camera.framerate = Fraction(1, 6)
camera.shutter_speed = 20000000 # 2 seconds
camera.exposure_mode = 'off'
camera.iso = 600
#-----------------------------------------------------------------------------------------------
def TakeDayImage():
time.sleep(0.5) # sleep for a little while so camera can get adjustments
if imagesToShootAtMotion > 1:
camera.capture_sequence([FilenameGenerator() + '_%02d.jpg' % i for i in range(imagesToShootAtMotion)],
format='jpeg', quality=imageQuality, use_video_port=False)
else:
camera.capture(FilenameGenerator() + ".jpg", 'jpeg', quality=imageQuality, use_video_port=False)
return
#-----------------------------------------------------------------------------------------------
def TakeNightImage():
CameraNightSettings()
time.sleep(2) # Give the camera a good long time to measure AWB
if imagesToShootAtMotion > 1:
camera.capture_sequence([FilenameGenerator() + '_%02d.jpg' % i for i in range(imagesToShootAtMotion)],
format='jpeg', quality=imageQuality, use_video_port=False)
else:
camera.capture(FilenameGenerator() + ".jpg", 'jpeg', quality=imageQuality, use_video_port=False)
CameraDaySettings() #Return to default mode for videocapture
return
#-----------------------------------------------------------------------------------------------
# Main program initialization and logic loop
print "PiCam started. All logging will go into picam.log"
with DetectMotion(camera) as output:
try:
CameraRecordingSettings()
camera.start_recording('/dev/null', format='h264', motion_output=output)
while True:
while not motionDetected:
UpdateAstral()
UpdateLED()
camera.wait_recording(1)
motionDetected = False
camera.stop_recording()
if astralIsDay:
TakeDayImage()
else:
TakeNightImage()
MotionLastStillCaptureTime = datetime.datetime.now()
CameraRecordingSettings()
camera.start_recording('/dev/null', format='h264', motion_output=output)
except Exception:
LOG.info('Exception', exc_info=True)
finally:
LOG.info("Motion detection ended")
camera.stop_recording()
GPIO.cleanup()
logging.info("PiCam Script ended")