Videosorveglianza con Raspberry Pi – Parte seconda

closeQuesto articolo è stato pubblicato 10 anni 5 mesi 5 giorni giorni fa quindi alcuni contenuti o informazioni presenti in esso potrebbero non essere più validi.

Per chi si fosse perso le puntate precedenti: Parte prima

Adesso passiamo ad installare il programma che ci permetterà, con relativa semplicità, di attivare la videosorveglianza: motion. Si installa con il comando

1
sudo apt-get install motion

Qualche minuto di pazienza e il programma sarà pronto. Adesso inizia il bello. Si deve configurare il programma, andando a lavorare sul suo elaborato file di configurazione. Qui un esempio (nello specifico quello che uso io, togliendo un po’ delle mille opzioni che ho lasciato inutilizzate)

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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
############################################################
# Daemon
############################################################
 
# Start in daemon (background) mode and release terminal (default: off)
daemon on
 
# File to store the process ID, also called pid file. (default: not defined)
;process_id_file /var/run/motion/motion.pid
 
############################################################
# Basic Setup Mode
############################################################
 
# Start in Setup-Mode, daemon disabled. (default: off)
setup_mode off
 
 
# Use a file to save logs messages, if not defined stderr and syslog is used. (default: not defined)
logfile /home/pi/controllo_movimento.log
 
# Level of log messages [1..9] (EMR, ALR, CRT, ERR, WRN, NTC, INF, DBG, ALL). (default: 6 / NTC)
log_level 7
 
# Filter to log messages by type (COR, STR, ENC, NET, DBL, EVT, TRK, VID, ALL). (default: ALL)
log_type all
 
###########################################################
# Capture device options
############################################################
 
# Videodevice to be used for capturing  (default /dev/video0)
# for FreeBSD default is /dev/bktr0
videodevice /dev/video0
 
# v4l2_palette allows to choose preferable palette to be use by motion
# to capture from those supported by your videodevice. (default: 17)
# E.g. if your videodevice supports both V4L2_PIX_FMT_SBGGR8 and
# V4L2_PIX_FMT_MJPEG then motion will by default use V4L2_PIX_FMT_MJPEG.
# Setting v4l2_palette to 2 forces motion to use V4L2_PIX_FMT_SBGGR8
# instead.
#
# Values :
# V4L2_PIX_FMT_SN9C10X : 0  'S910'
# V4L2_PIX_FMT_SBGGR16 : 1  'BYR2'
# V4L2_PIX_FMT_SBGGR8  : 2  'BA81'
# V4L2_PIX_FMT_SPCA561 : 3  'S561'
# V4L2_PIX_FMT_SGBRG8  : 4  'GBRG'
# V4L2_PIX_FMT_SGRBG8  : 5  'GRBG'
# V4L2_PIX_FMT_PAC207  : 6  'P207'
# V4L2_PIX_FMT_PJPG    : 7  'PJPG'
# V4L2_PIX_FMT_MJPEG   : 8  'MJPEG'
# V4L2_PIX_FMT_JPEG    : 9  'JPEG'
# V4L2_PIX_FMT_RGB24   : 10 'RGB3'
# V4L2_PIX_FMT_SPCA501 : 11 'S501'
# V4L2_PIX_FMT_SPCA505 : 12 'S505'
# V4L2_PIX_FMT_SPCA508 : 13 'S508'
# V4L2_PIX_FMT_UYVY    : 14 'UYVY'
# V4L2_PIX_FMT_YUYV    : 15 'YUYV'
# V4L2_PIX_FMT_YUV422P : 16 '422P'
# V4L2_PIX_FMT_YUV420  : 17 'YU12'
#
v4l2_palette 17
 
# The video input to be used (default: -1)
# Should normally be set to 0 or 1 for video/TV cards, and -1 for USB cameras
input -1
 
# Rotate image this number of degrees. The rotation affects all saved images as
# well as movies. Valid values: 0 (default = no rotation), 90, 180 and 270.
rotate 0
 
# Image width (pixels). Valid range: Camera dependent, default: 352
width 1024
 
# Image height (pixels). Valid range: Camera dependent, default: 288
height 768
 
# Maximum number of frames to be captured per second.
# Valid range: 2-100. Default: 100 (almost no limit).
framerate 4
 
# URL to use if you are using a network camera, size will be autodetected (incl http:// ftp:// mjpg:// or file:///)
# Must be a URL that returns single jpeg pictures or a raw mjpeg stream. Default: Not defined
;netcam_url http://127.0.0.1/cgi-bin/raspicam.sh
 
# Username and password for network camera (only if required). Default: not defined
# Syntax is user:password
; netcam_userpass value
 
# The setting for keep-alive of network socket, should improve performance on compatible net cameras.
# off:   The historical implementation using HTTP/1.0, closing the socket after each http request.
# force: Use HTTP/1.0 requests with keep alive header to reuse the same connection.
# on:    Use HTTP/1.1 requests that support keep alive as default.
# Default: off
netcam_keepalive off
 
# Let motion regulate the brightness of a video device (default: off).
# The auto_brightness feature uses the brightness option as its target value.
# If brightness is zero auto_brightness will adjust to average brightness value 128.
# Only recommended for cameras without auto brightness
auto_brightness off
 
# Set the initial brightness of a video device.
# If auto_brightness is enabled, this value defines the average brightness level
# which Motion will try and adjust to.
# Valid range 0-255, default 0 = disabled
brightness 0
 
# Set the contrast of a video device.
# Valid range 0-255, default 0 = disabled
contrast 0
 
# Set the saturation of a video device.
# Valid range 0-255, default 0 = disabled
saturation 0
 
############################################################
# OpenMax/MMAL camera support for Raspberry Pi
############################################################
mmalcam_name vc.ril.camera
#mmalcam_control_params
#mmalcam_raw_capture_file /home/pi/motion-mmal.capture
 
# Switch this setting to "on" to use the still image mode of the Pi's camera
# instead of video. This gives a wider field of view, but requires
# a much slower frame-rate to achieve exposure stability
# (e.g. 0.25 fps or slower). You can use the minimum_frame_time
# parameter above to achieve this
 
mmalcam_use_still off
 
 
############################################################
# Round Robin (multiple inputs on same video device name)
############################################################
 
# Number of frames to capture in each roundrobin step (default: 1)
roundrobin_frames 1
 
# Number of frames to skip before each roundrobin step (default: 1)
roundrobin_skip 1
 
# Try to filter out noise generated by roundrobin (default: off)
switchfilter off
 
 
############################################################
# Motion Detection Settings:
############################################################
 
# Threshold for number of changed pixels in an image that
# triggers motion detection (default: 1500)
threshold 5000
 
# Automatically tune the threshold down if possible (default: off)
threshold_tune off
 
# Noise threshold for the motion detection (default: 32)
noise_level 32
 
# Automatically tune the noise threshold (default: on)
noise_tune on
 
# Despeckle motion image using (e)rode or (d)ilate or (l)abel (Default: not defined)
# Recommended value is EedDl. Any combination (and number of) of E, e, d, and D is valid.
# (l)abeling must only be used once and the 'l' must be the last letter.
# Comment out to disable
despeckle_filter EedDl
 
# Detect motion in predefined areas (1 - 9). Areas are numbered like that:  1 2 3
# A script (on_area_detected) is started immediately when motion is         4 5 6
# detected in one of the given areas, but only once during an event.        7 8 9
# One or more areas can be specified with this option. Take care: This option
# does NOT restrict detection to these areas! (Default: not defined)
; area_detect value
 
# PGM file to use as a sensitivity mask.
# Full path name to. (Default: not defined)
; mask_file value
 
# Dynamically create a mask file during operation (default: 0)
# Adjust speed of mask changes from 0 (off) to 10 (fast)
smart_mask_speed 0
 
# Ignore sudden massive light intensity changes given as a percentage of the picture
# area that changed intensity. Valid range: 0 - 100 , default: 0 = disabled
lightswitch 0
 
# Picture frames must contain motion at least the specified number of frames
# in a row before they are detected as true motion. At the default of 1, all
# motion is detected. Valid range: 1 to thousands, recommended 1-5
minimum_motion_frames 1
 
# Specifies the number of pre-captured (buffered) pictures from before motion
# was detected that will be output at motion detection.
# Recommended range: 0 to 5 (default: 0)
# Do not use large values! Large values will cause Motion to skip video frames and
# cause unsmooth movies. To smooth movies use larger values of post_capture instead.
pre_capture 0 
 
# Number of frames to capture after motion is no longer detected (default: 0)
post_capture 0
 
# Event Gap is the seconds of no motion detection that triggers the end of an event.
# An event is defined as a series of motion images taken within a short timeframe.
# Recommended value is 60 seconds (Default). The value -1 is allowed and disables
# events causing all Motion to be written to one single movie file and no pre_capture.
# If set to 0, motion is running in gapless mode. Movies don't have gaps anymore. An
# event ends right after no more motion is detected and post_capture is over.
event_gap 60
 
# Maximum length in seconds of a movie
# When value is exceeded a new movie file is created. (Default: 0 = infinite)
max_movie_time 0
 
# Always save images even if there was no motion (default: off)
emulate_motion off
 
 
############################################################
# Image File Output
############################################################
 
# Output 'normal' pictures when motion is detected (default: on)
# Valid values: on, off, first, best, center
# When set to 'first', only the first picture of an event is saved.
# Picture with most motion of an event is saved when set to 'best'.
# Picture with motion nearest center of picture is saved when set to 'center'.
# Can be used as preview shot for the corresponding movie.
output_pictures on
 
# Output pictures with only the pixels moving object (ghost images) (default: off)
output_debug_pictures off
 
# The quality (in percent) to be used by the jpeg compression (default: 75)
quality 75
 
# Type of output images
# Valid values: jpeg, ppm (default: jpeg)
picture_type jpeg
 
############################################################
# FFMPEG related options
# Film (movies) file output, and deinterlacing of the video input
# The options movie_filename and timelapse_filename are also used
# by the ffmpeg feature
############################################################
 
# Use ffmpeg to encode movies in realtime (default: off)
ffmpeg_output_movies off
 
# Use ffmpeg to make movies with only the pixels moving
# object (ghost images) (default: off)
ffmpeg_output_debug_movies off
 
# Use ffmpeg to encode a timelapse movie
# Default value 0 = off - else save frame every Nth second
ffmpeg_timelapse 0
 
# The file rollover mode of the timelapse video
# Valid values: hourly, daily (default), weekly-sunday, weekly-monday, monthly, manual
ffmpeg_timelapse_mode daily
 
# Bitrate to be used by the ffmpeg encoder (default: 400000)
# This option is ignored if ffmpeg_variable_bitrate is not 0 (disabled)
ffmpeg_bps 500000
 
# Enables and defines variable bitrate for the ffmpeg encoder.
# ffmpeg_bps is ignored if variable bitrate is enabled.
# Valid values: 0 (default) = fixed bitrate defined by ffmpeg_bps,
# or the range 2 - 31 where 2 means best quality and 31 is worst.
ffmpeg_variable_bitrate 0
 
# Codec to used by ffmpeg for the video compression.
# Timelapse mpegs are always made in mpeg1 format independent from this option.
# Supported formats are: mpeg1 (ffmpeg-0.4.8 only), mpeg4 (default), and msmpeg4.
# mpeg1 - gives you files with extension .mpg
# mpeg4 or msmpeg4 - gives you files with extension .avi
# msmpeg4 is recommended for use with Windows Media Player because
# it requires no installation of codec on the Windows client.
# swf - gives you a flash film with extension .swf
# flv - gives you a flash video with extension .flv
# ffv1 - FF video codec 1 for Lossless Encoding ( experimental )
# mov - QuickTime ( testing )
# ogg - Ogg/Theora ( testing )
ffmpeg_video_codec mpeg4
 
# Use ffmpeg to deinterlace video. Necessary if you use an analog camera
# and see horizontal combing on moving objects in video or pictures.
# (default: off)
ffmpeg_deinterlace off
 
############################################################
# Snapshots (Traditional Periodic Webcam File Output)
############################################################
 
# Make automated snapshot every N seconds (default: 0 = disabled)
snapshot_interval 0
 
 
############################################################
# Text Display
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second, %T = HH:MM:SS,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level, \n = new line,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event - do not use with text_event!
# You can put quotation marks around the text to allow
# leading spaces
############################################################
 
# Locate and draw a box around the moving object.
# Valid values: on, off, preview (default: off)
# Set to 'preview' will only draw a box in preview_shot pictures.
locate_motion_mode on
 
# Set the look and style of the locate box if enabled.
# Valid values: box, redbox, cross, redcross (default: box)
# Set to 'box' will draw the traditional box.
# Set to 'redbox' will draw a red box.
# Set to 'cross' will draw a little cross to mark center.
# Set to 'redcross' will draw a little red cross to mark center.
locate_motion_style redcross
 
# Draws the timestamp using same options as C function strftime(3)
# Default: %Y-%m-%d\n%T = date in ISO format and time in 24 hour clock
# Text is placed in lower right corner
text_right %Y-%m-%d\n%T-%q
 
# Draw a user defined text on the images using same options as C function strftime(3)
# Default: Not defined = no text
# Text is placed in lower left corner
; text_left CAMERA %t
 
# Draw the number of changed pixed on the images (default: off)
# Will normally be set to off except when you setup and adjust the motion settings
# Text is placed in upper right corner
text_changes on
 
# This option defines the value of the special event conversion specifier %C
# You can use any conversion specifier in this option except %C. Date and time
# values are from the timestamp of the first image in the current event.
# Default: %Y%m%d%H%M%S
# The idea is that %C can be used filenames and text_left/right for creating
# a unique identifier for each event.
text_event %Y%m%d%H%M%S
 
# Draw characters at twice normal size on images. (default: off)
text_double on
 
 
############################################################
# Target Directories and filenames For Images And Films
# For the options snapshot_, picture_, movie_ and timelapse_filename
# you can use conversion specifiers
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# Quotation marks round string are allowed.
############################################################
 
# Target base directory for pictures and films
# Recommended to use absolute path. (Default: current working directory)
target_dir /home/pi/Pictures
 
# File path for snapshots (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-snapshot
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-snapshot
# File extension .jpg or .ppm is automatically added so do not include this.
# Note: A symbolic link called lastsnap.jpg created in the target_dir will always
# point to the latest snapshot, unless snapshot_filename is exactly 'lastsnap'
snapshot_filename %v-%Y%m%d%H%M%S-snapshot
 
# File path for motion triggered images (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-%q
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-%q
# File extension .jpg or .ppm is automatically added so do not include this
# Set to 'preview' together with best-preview feature enables special naming
# convention for preview shots. See motion guide for details
picture_filename %v-%Y%m%d%H%M%S-%q
 
# File path for motion triggered ffmpeg films (movies) relative to target_dir
# Default: %v-%Y%m%d%H%M%S
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H%M%S
# File extension .mpg or .avi is automatically added so do not include this
# This option was previously called ffmpeg_filename
movie_filename %v-%Y%m%d%H%M%S
 
# File path for timelapse movies relative to target_dir
# Default: %Y%m%d-timelapse
# Default value is near equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d-timelapse
# File extension .mpg is automatically added so do not include this
timelapse_filename %Y%m%d-timelapse
 
############################################################
# Global Network Options
############################################################
# Enable or disable IPV6 for http control and stream (default: off )
ipv6_enabled off
 
############################################################
# Live Stream Server
############################################################
 
# The mini-http server listens to this port for requests (default: 0 = disabled)
stream_port 8091
 
# Quality of the jpeg (in percent) images produced (default: 50)
stream_quality 50
 
# Output frames at 1 fps when no motion is detected and increase to the
# rate given by stream_maxrate when motion is detected (default: off)
stream_motion on
 
# Maximum framerate for stream streams (default: 1)
stream_maxrate 10
 
# Restrict stream connections to localhost only (default: on)
stream_localhost off
 
# Limits the number of images per connection (default: 0 = unlimited)
# Number can be defined by multiplying actual stream rate by desired number of seconds
# Actual stream rate is the smallest of the numbers framerate and stream_maxrate
stream_limit 0
 
# Set the authentication method (default: 0)
# 0 = disabled
# 1 = Basic authentication
# 2 = MD5 digest (the safer authentication)
stream_auth_method 0
 
# Authentication for the stream. Syntax username:password
# Default: not defined (Disabled)
; stream_authentication username:password
 
 
############################################################
# HTTP Based Control
############################################################
 
# TCP/IP port for the http server to listen on (default: 0 = disabled)
webcontrol_port 0
 
# Restrict control connections to localhost only (default: on)
webcontrol_localhost off
 
# Output for http server, select off to choose raw text plain (default: on)
webcontrol_html_output on
 
# Authentication for the http based control. Syntax username:password
# Default: not defined (Disabled)
; webcontrol_authentication username:password
 
 
 
 
############################################################
# External Commands, Warnings and Logging:
# You can use conversion specifiers for the on_xxxx commands
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# %f = filename with full path
# %n = number indicating filetype
# Both %f and %n are only defined for on_picture_save,
# on_movie_start and on_movie_end
# Quotation marks round string are allowed.
############################################################
 
# Do not sound beeps when detecting motion (default: on)
# Note: Motion never beeps when running in daemon mode.
quiet on
 
# Command to be executed when an event starts. (default: none)
# An event starts at first motion detected after a period of no motion defined by event_gap
; on_event_start value
 
# Command to be executed when an event ends after a period of no motion
# (default: none). The period of no motion is defined by option event_gap.
on_event_end rm /home/pi/Pictures/*.jpg
 
# Command to be executed when a picture (.ppm|.jpg) is saved (default: none)
# To give the filename as an argument to a command append it with %f
on_picture_save python /home/pi/tweepy/tweet.py %f
 
 
# Command to be executed when a motion frame is detected (default: none)
; on_motion_detected value
 
# Command to be executed when motion in a predefined area is detected
# Check option 'area_detect'.   (default: none)
; on_area_detected value
 
# Command to be executed when a movie file (.mpg|.avi) is created. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_start value
 
# Command to be executed when a movie file (.mpg|.avi) is closed. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_end value
 
# Command to be executed when a camera can't be opened or if it is lost
# NOTE: There is situations when motion don't detect a lost camera!
# It depends on the driver, some drivers dosn't detect a lost camera at all
# Some hangs the motion thread. Some even hangs the PC! (default: none)
; on_camera_lost value

Paura, eh? Non vi preoccupate, i parametri utili sono semplici ed abbastanza intuitivi, adesso li analizziamo uno per volta. Tutti i parametri che non affronto, semplicemente non li ho utilizzati, nella ricca documentazione trovate tutte le funzioni extra che potete aggiungere al vostro sistema.

1
daemon on

Questo dice al programma che quando viene avviato deve rilasciare la console libera e deve funzionare come demone (“servizio”, in lingua Windows). E’ bene tenerlo ad OFF durante tutte le vostre prove, in modo da vedere a video cosa sta combinando il programma e sopratutto se ci sono errori

1
logfile [percorso]

il file dentro cui saranno salvati tutti i log (quelli che vedete a video con l’impostazione “daemon off” appena vista, per intenderci). Consiglio personale: NON chiamate questo file “motion” o con un nome che contenga la parola “motion”, questo per evitare innumerevoli casini quando andremo a sviluppare l’applicazione

1
log_level 7

Quante cose devo memorizzare nel file di log? Dopo un po’ di prove, ho raggiungo la conclusione che “7” è il livello adatto per capire cosa sta succedendo, senza morire sommersi di informazioni inutili

1
videodevice /dev/video0

Questa è la videocamera che verrà utilizzata per rilevare il movimento, il default è la videocamera che avete appena collegato al Raspberry Pi e che avete provato

1
2
width 768
height 1024

Questa è la dimensione del video che verrà ripreso e dei fermo immagine che verranno salvati in caso di movimento. Assicuratevi che siano valori divisibili per 16 e che non superino la risoluzione della videocamera (1920×1080). Più solo alti, più il processore verrà messo sotto stress, ma se sono stroppo bassi perderete dettaglio nella registrazione. Con 1024×768 mi pare di aver trovato un buon compromesso

1
framerate 4

Quante foto devono essere salvate per ogni secondo? Più il valore è alto più la CPU sarà sotto stress, ma meno dettaglio avrete in caso di movimenti rapidi. L’unica è fare un po’ di tentativi. Per me 4 è un valore buono (vedo la faccia di chi entra in casa tutte le volte)

1
netcam_url [indirizzo]

Se non usate la videocamera del Raspberry Pi, potete collegarvi ad una videocamera IP (ma dovete avere le documentazione)

1
threshold 5000

Questo è un parametro importante. Per identificare il movimento il sistema fa un banale controllo: “quanti pixel sono cambiati dall’immagine precedente all’attuale?”. In un frame da 1024×768 i pixel sono 786.432, la domanda che ci si deve porre è “che percentuale dell’immagine deve cambiare perché io sia avvisato?”. La risposta è solo una: provare e provare

1
event_gap 60

dopo quanti secondi senza movimento devo identificare l’evento come terminato? Questo parametro ci servirà più tardi.

1
output_picture on

Devo salvare le immagini del movimento? con l’importazione ad “on2 la risposta è “sì, salvale tutte”

1
ffmpeg_output_movies OFF

Il sistema può anche salvare dei video, nei formati più disparati, per poterlo fare dovere installare un codec MPEG4 o simile, l’ho fatto, ma non mi è tornato utile, non salvo i video, ma solo le immagini

1
snapshot_interval 0

Se volete ottenere una foto ogni “x” secondi, mettete un valore numerico qui, l’immagine verrà salvata anche se non c’è movimento

1
2
locate_motion_mode on
locate_motion_style redcross

Se la domanda che vi ponete è “ma cosa si è mosso?” questa è la soluzione, una crocetta rossa identificherà il centro del movimento

1
2
3
4
text_right
text_left
text_changes on
text_double on

Il sistema metterà in sovraimpressione il testo che deciderete voi, così da identificare l’immgine. La “text_changes” mostra quanti pixel sono cambiati, vi aiuta per capire come impostare il parametro “treshold”. La “text_double” se impostata ad “on” renderà un po’ più leggibili le scritte se l’immagine è ad alta risoluzione

1
target_dir /home/pi/Pictures

Questa è la cartella dove verranno salvate tutte le immagini registrate. Se contate di non cancellarle mai è bene che sia un posto sufficientemente capiente, tipo un disco USB

1
[media]_filename

Il nome che viene assegnato al file salvato, io ho lasciato tutto impostato al default

1
stream_port 8091

Volete vedere cosa sta osservando la videocamera? Puntate il browser all’indirizzo http://[indirizzo IP del Raspberry]:8091 ed avrete la risposta. Se non è una cosa che vi interessa, mettete “0” al posto di “8091”. Non so perché, ma su Chrome lo streaming non va, provate con un altro browser prima di impazzire 2 giorni per capire cosa potrebbe non andare bene sulla vostra scheda Raspberry Pi

1
2
3
on_[evento]
on_event_end rm /home/pi/Pictures/*.jpg
on_picture_save python /home/pi/tweepy/tweet.py %f

Questa parte è importante! Cosa deve fare il programma quando succede qualcosa? Il cuore della funzionalità è qui.
Partiamo da “on_picture_save”. Ogni volta che un’immagine viene salvata io eseguo uno script in Python(lo vedremo oltre) che prende l’immagine salvata e la twitta (sì, posta l’immagine su twitter, con un apposito account protetto e citando il mio account principale: nessuno oltre me può vedere quell’immagine). Una volta twittata per me è inutile che questa stia sul Raspberry Pi, pertanto, alla fine dell’evento (dopo i secondi indicati nel parametro “event_gap”) il comando “rm /home/pi/Pictures/*.jpg” cancellerà tutte le foto salvate

Bene, abbiamo il file configurato. Ma dove lo mettiamo? Il file si deve chiamare “motion.conf” e deve stare nella cartella “/home/pi/.motion”. Commentate le righe relative agli eventi “on_[qualcosa]” anteponendo un “;” o un “#”, e impostate l’opzione “daemon” a “off”, salvate il file ed eseguite il programma “/home/pi/motion-mmal/motion”
Nota molto bene: in teoria motion parte digitando “motion” da una cartella qualunque, ma in questo caso non trova la videocamera, almeno nel mio caso.

Se tutto va come deve (no, la prima volta non va mai tutto come deve) il programma partirà, vi dirà che ha attivato la videocamera che he (se lo avete attivato) ha anche attivato il server web per lo streaming, una cosa del genere. Il LED rosso della videocamera si accenderà indicando che è attiva.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[-1242438816] [NTC] [ALL] [Jun 08 11:47:50] motion_startup: Using log type (ALL) log level (INF)
[-1242438816] [NTC] [ALL] [Jun 08 11:47:50] motion_startup: Motion running as daemon process
[-1242438816] [NTC] [ENC] [Jun 08 11:47:50] ffmpeg_init: ffmpeg LIBAVCODEC_BUILD 3482368 LIBAVFORMAT_BUILD 3478785
[0] [NTC] [ALL] [Jun 08 11:47:50] main: Thread 1 is from /home/pi/.motion/motion.conf
[0] [NTC] [ALL] [Jun 08 11:47:50] main: Thread 1 is device: /dev/video0 input -1
[0] [NTC] [ALL] [Jun 08 11:47:50] main: Stream port 8091
[0] [NTC] [ALL] [Jun 08 11:47:50] main: Waiting for threads to finish, pid: 5938
[1] [NTC] [ALL] [Jun 08 11:47:50] motion_init: Thread 1 started , motion detection Enabled
[1] [ALR] [VID] [Jun 08 11:47:50] mmalcam_start: MMAL Camera thread starting... for camera (vc.ril.camera) of 1024 x 768 at 4 fps
[1] [ALR] [VID] [Jun 08 11:47:50] mmalcam_start: MMAL Camera using video capture
[1] [NTC] [VID] [Jun 08 11:47:50] MMAL camera component created
[1] [NTC] [ALL] [Jun 08 11:47:50] image_ring_resize: Resizing pre_capture buffer to 1 items
[1] [NTC] [STR] [Jun 08 11:47:50] http_bindsock: motion-stream testing : IPV4 addr: 0.0.0.0 port: 8091
[1] [NTC] [STR] [Jun 08 11:47:50] http_bindsock: motion-stream Bound : IPV4 addr: 0.0.0.0 port: 8091
[1] [NTC] [ALL] [Jun 08 11:47:50] motion_init: Started motion-stream server in port 8091 auth Disabled

Adesso provate a passare davanti alla videocamera con la mano, voi stessi o banalmente generate un movimento davanti ad essa ed eco che il log vi dirà (sì, il file di log parla ed è buona norma ascoltarlo, sempre) una cosa del genere

1
2
3
4
5
6
7
[1] [NTC] [ALL] [Jun 08 10:52:18] motion_detected: Motion detected - starting event 1
[1] [NTC] [EVT] [Jun 08 10:52:19] event_newfile: File of type 1 saved to: /home/pi/Pictures/01-20140608105218-02.jpg
[1] [NTC] [EVT] [Jun 08 10:52:20] event_newfile: File of type 1 saved to: /home/pi/Pictures/01-20140608105219-00.jpg
[1] [NTC] [EVT] [Jun 08 10:52:21] event_newfile: File of type 1 saved to: /home/pi/Pictures/01-20140608105220-00.jpg
[1] [NTC] [EVT] [Jun 08 10:52:23] event_newfile: File of type 1 saved to: /home/pi/Pictures/01-20140608105221-00.jpg
[1] [NTC] [EVT] [Jun 08 10:52:24] event_newfile: File of type 1 saved to: /home/pi/Pictures/01-20140608105223-00.jpg
[1] [NTC] [ALL] [Jun 08 10:53:23] motion_loop: End of event 1

Terminate l’esecuzione del programma con un bel Ctrl+C andare a vedere nella cartella /home/pi/Pictures/ la presenza dei file salvati. Questi conterranno il movimento rilevato.

(continua…)

2 pensieri riguardo “Videosorveglianza con Raspberry Pi – Parte seconda”

Nota importante, da leggere prima di commentare

Questo è un blog scritto per passione, non fornisco quindi risposte di tipo professionale, se avete bisogno di un aiuto tecnico rivolgetevi ad un professionista di fiducia, non offendetevi se mi astengo dal rispondere. Vi ringrazio per la comprensione.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.