-
Notifications
You must be signed in to change notification settings - Fork 174
/
speed-cam.py
2022 lines (1887 loc) · 83.8 KB
/
speed-cam.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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""
speed-cam.py written by Claude Pageau
Windows, Unix, Raspberry (Pi) - python opencv2 Object Speed tracking
using picamera module, Web Cam or RTSP IP Camera
GitHub Repo at https://github.com/pageauc/speed-camera
Post issue to Github.
This is a python openCV object speed tracking demonstration program.
It will detect speed in the field of view and use openCV to calculate the
largest contour and return its x,y center coordinate. The image is tracked for
a specified loop count and the final speed is calculated.
Note: Variables for this program are stored in config.py
Some of this code is based on a YouTube tutorial by
Kyle Hounslow using C here https://www.youtube.com/watch?v=X6rPdRZzgjg
Thanks to Adrian Rosebrock jrosebr1 at http://www.pyimagesearch.com
for the PiVideoStream Class code available on github at
https://github.com/jrosebr1/imutils/blob/master/imutils/video/pivideostream.py
Here is my YouTube video demonstrating a previous speed tracking demo
program using a Raspberry Pi B2 https://youtu.be/09JS7twPBsQ
and a fun speed lapse video https://youtu.be/-xdB_x_CbC8
Installation
------------
Requires a Raspberry Pi or compatible, Windows, Unix PC or Mac with webcam or RTSP IP Camera.
or a virtual machine unix distro eg Debian. Runs best under python3 but code is compatible with python2.
Works with RPI camera module using picamera or libpicamera2 python module.
See github wiki for detail https://github.com/pageauc/speed-camera/wiki
Install from a GitHub download, Docker or using Curl install from logged in SSH session per commands below.
Code should run on a non RPI platform using a Web Cam or RTSP ip cam
curl -L https://raw.github.com/pageauc/rpi-speed-camera/master/speed-install.sh | bash
or
wget https://raw.github.com/pageauc/rpi-speed-camera/master/speed-install.sh
chmod +x speed-install.sh
./speed-install.sh
./speed-cam.py
Note to Self - Look at eliminating python variable camel case and use all snake naming
"""
from __future__ import print_function
PROG_VER = "13.2" # current version of this python script
print('Loading Wait...')
import os
import sys
import time
import datetime
import glob
import shutil
import logging
import sqlite3
import numpy as np
# import the main strmcam launch module
try:
from strmcam import strmcam
except Exception as err_msg:
print("ERROR: %s" % err_msg)
sys.exit(1)
# Get information about this script including name, launch path, etc.
# This allows script to be renamed or relocated to another directory
mypath = os.path.abspath(__file__) # Find the full path of this python script
# get the path location only (excluding script name)
baseDir = mypath[0 : mypath.rfind("/") + 1]
baseFileName = mypath[mypath.rfind("/") + 1 : mypath.rfind(".")]
PROG_NAME = os.path.basename(__file__)
HORIZ_LINE = "----------------------------------------------------------------------"
print(HORIZ_LINE)
print("%s %s written by Claude Pageau" % (PROG_NAME, PROG_VER))
print("Motion Track Largest Moving Object and Calculate Speed per Calibration.")
print(HORIZ_LINE)
# This is a dictionary of the default settings for speed-cam.py
# If you don't want to use a config.py file these will create the required
# variables with default values. Change dictionary values if you want different
# variable default values.
# A message will be displayed if a variable is Not imported from config.py.
# Note: plugins can override default and config.py values if plugins are
# enabled. This happens after config.py variables are imported
default_settings = {
"CALIBRATE_ON": True,
"ALIGN_CAM_ON": False,
"ALIGN_DELAY_SEC": 2,
"SHOW_SETTINGS_ON": False,
"CAL_OBJ_PX_L2R": 90,
"CAL_OBJ_MM_L2R": 4700.0,
"CAL_OBJ_PX_R2L": 95,
"CAL_OBJ_MM_R2L": 4700.0,
"PLUGIN_ENABLE_ON": False,
"PLUGIN_NAME": "picam240",
"GUI_WINDOW_ON": False,
"GUI_THRESH_WIN_ON": False,
"GUI_CROP_WIN_ON": False,
"LOG_VERBOSE_ON": True,
"LOG_FPS_ON": False,
"LOG_DATA_TO_CSV": False,
"LOG_TO_FILE_ON": False,
"LOG_FILE_PATH": "speed-cam.log",
"MO_SPEED_MPH_ON": False,
"MO_TRACK_EVENT_COUNT": 5,
"MO_MIN_AREA_PX": 100,
"MO_LOG_OUT_RANGE_ON": True,
"MO_MAX_X_DIFF_PX": 20,
"MO_MIN_X_DIFF_PX": 1,
"MO_X_LR_SIDE_BUFF_PX": 10,
"MO_TRACK_TIMEOUT_SEC": 0.5,
"MO_EVENT_TIMEOUT_SEC": 0.3,
"MO_MAX_SPEED_OVER": 0,
"MO_CROP_AUTO_ON": False,
"MO_CROP_X_LEFT": 50,
"MO_CROP_X_RIGHT": 250,
"MO_CROP_Y_UPPER": 90,
"MO_CROP_Y_LOWER": 150,
"CAMERA": "pilibcam",
"CAM_LOCATION": "Front Window",
"USBCAM_SRC": 0,
"RTSPCAM_SRC": "rtsp://user:password@IP:554/path",
"IM_SIZE": (320, 240),
"IM_VFLIP": False,
"IM_HFLIP": False,
"IM_ROTATION": 0,
"IM_FRAMERATE": 30,
"IM_DIR_PATH": "media/images",
"IM_PREFIX": "speed-",
"IM_FORMAT_EXT": ".jpg",
"IM_JPG_QUALITY": 95,
"IM_JPG_OPTIMIZE_ON": False,
"IM_SAVE_4AI_ON": False,
"IM_SAVE_4AI_POS_DIR": "media/ai/pos",
"IM_SAVE_4AI_NEG_DIR": "media/ai/pos",
"IM_SAVE_4AI_DAY_THRESH": 10,
"IM_SAVE_4AI_NEG_TIMER_SEC": 60 * 60 * 6,
"IM_FIRST_AND_LAST_ON": False,
"IM_SHOW_CROP_AREA_ON": True,
"IM_SHOW_SPEED_FILENAME_ON": False,
"IM_SHOW_TEXT_ON": True,
"IM_SHOW_TEXT_BOTTOM_ON": True,
"IM_FONT_SIZE_PX": 12,
"IM_FONT_THICKNESS": 2,
"IM_FONT_SCALE": 0.5,
"IM_FONT_COLOR": (255, 255, 255),
"IM_BIGGER": 3.0,
"IM_MAX_FILES": 0,
"IM_SUBDIR_MAX_FILES": 1000,
"IM_SUBDIR_MAX_HOURS": 0,
"IM_RECENT_MAX_FILES": 100,
"IM_RECENT_DIR_PATH": "media/recent",
"SPACE_TIMER_HRS": 0,
"SPACE_FREE_MB": 500,
"SPACE_MEDIA_DIR": "media/images",
"SPACE_FILE_EXT ": "jpg",
"CV_SHOW_CIRCLE_ON": False,
"CV_CIRCLE_SIZE_PX": 5,
"CV_LINE_WIDTH_PX": 1,
"CV_WINDOW_BIGGER": 1.0,
"BLUR_SIZE": 10,
"THRESHOLD_SENSITIVITY": 20,
"DB_DIR": "data",
"DB_NAME": "speed_cam.db",
"DB_TABLE": "speed",
"GRAPH_PATH": "media/graphs",
"GRAPH_ADD_DATE_TO_FILENAME": False,
"GRAPH_RUN_TIMER_HOURS": 0.5,
"GRAPH_RUN_LIST": [
["hour", 2, 0],
["hour", 7, 10],
["hour", 14, 10],
["day", 28, 0],
],
"WEB_SERVER_PORT": 8080,
"WEB_SERVER_ROOT": "media",
"WEB_PAGE_TITLE": "SPEED-CAMERA Media",
"WEB_PAGE_REFRESH_ON": True,
"WEB_PAGE_REFRESH_SEC": "900",
"WEB_PAGE_BLANK_ON": False,
"WEB_IMAGE_HEIGHT": "768",
"WEB_IFRAME_WIDTH_PERCENT": "70%",
"WEB_IFRAME_WIDTH": "100%",
"WEB_IFRAME_HEIGHT": "100%",
"WEB_MAX_LIST_ENTRIES": 0,
"WEB_LIST_HEIGHT": "768",
"WEB_LIST_BY_DATETIME_ON": True,
"WEB_LIST_SORT_DESC_ON": True,
"IM_SHOW_SIGN_ON": False,
"IM_SIGN_RESIZE": (1280, 720),
"IM_SIGN_TEXT_XY": (100, 675),
"IM_SIGN_FONT_SCALE": 30.0,
"IM_SIGN_FONT_THICK_PX": 60,
"IM_SIGN_FONT_COLOR": (255, 255, 255),
"IM_SIGN_TIMEOUT_SEC": 5,
}
# Color data for OpenCV lines and text
cvWhite = (255, 255, 255)
cvBlack = (0, 0, 0)
cvBlue = (255, 0, 0)
cvGreen = (0, 255, 0)
cvRed = (0, 0, 255)
QUOTE = '"' # Used for creating QUOTE delimited log file of speed data
FIX_MSG = """
---------- Upgrade Instructions -----------
To Fix Problem Run ./menubox.sh UPGRADE menu pick.
After upgrade newest config.py will be named config.py.new
In SSH or terminal perform the following commands
to update to latest config.py
cd ~/speed-camera
cp config.py config.py.bak
cp config.py.new config.py
Then Edit nsno config.py and transfer any customized settings
from config.py.bak File to config.py
-------------------------------------------
Wait 5 sec ....
"""
# Check for config.py variable file and import. Warn if file not Found.
# Logging is not used since the LOG_FILE_PATH variable is needed before
# setting up logging
configFilePath = os.path.join(baseDir, "config.py")
if os.path.exists(configFilePath):
# Read Configuration variables from config.py file
try:
from config import *
except Exception as err_msg:
print("WARN : %s" % err_msg)
else:
print("WARN : Missing config.py file - File Not Found %s" % configFilePath)
# Check if variables were imported from config.py. If not create variable using
# the values in the default_settings dictionary above.
warn_msg = False
for key, val in default_settings.items():
try:
exec(key)
except NameError:
print("WARN : config.py Variable Not Found. Setting " + key + " = " + str(val))
exec(key + "=val")
warn_msg = True
if warn_msg:
print(FIX_MSG)
time.sleep(5)
# Now that variables are imported from config.py Setup Logging since we have LOG_FILE_PATH
if LOG_TO_FILE_ON:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(funcName)-10s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
filename=LOG_FILE_PATH,
filemode="w",
)
elif LOG_VERBOSE_ON:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(funcName)-10s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
else:
logging.basicConfig(
level=logging.CRITICAL,
format="%(asctime)s %(levelname)-8s %(funcName)-10s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# Do a quick check to see if the sqlite database directory path exists
DB_DIR_PATH = os.path.join(baseDir, DB_DIR)
if not os.path.exists(DB_DIR_PATH): # Check if database directory exists
os.makedirs(DB_DIR_PATH) # make directory if Not Found
DB_PATH = os.path.join(DB_DIR_PATH, DB_NAME) # Create path to db file
try: # Check to see if opencv is installed
import cv2
except ImportError:
logging.error("Could Not import cv2 library")
if sys.version_info > (2, 9):
logging.error("python3 failed to import cv2")
logging.error("Try installing opencv for python3")
logging.error("For RPI See https://github.com/pageauc/opencv3-setup")
else:
logging.error("python2 failed to import cv2")
logging.error("Try running menubox.sh then UPGRADE menu pick.")
logging.error("%s %s Exiting Due to Error", PROG_NAME, PROG_VER)
sys.exit(1)
# Import a single variable from the search_config.py file
# This is done to auto create a media/search directory
try:
from search_config import search_dest_path
except ImportError:
search_dest_path = "media/search"
logging.warning("Problem importing search_dest_path variable")
logging.info("Setting default value search_dest_path = %s", search_dest_path)
# Check for user_motion_code.py file to import and error out if not found.
userMotionFilePath = os.path.join(baseDir, "user_motion_code.py")
USER_MOTION_CODE_ON = True # Set Flag to run user_motion_code.py
if os.path.isfile(userMotionFilePath):
try:
import user_motion_code
except Exception as err_msg:
print("WARN: %s" % err_msg)
# set flag to ignore running user motion code after succsessful track.
USER_MOTION_CODE_ON = False
else:
print("WARN : import Failed. File Not Found %s" % userMotionFilePath)
USER_MOTION_CODE_ON = False
# Import Settings from specified plugin if PLUGIN_ENABLE_ON=True
if PLUGIN_ENABLE_ON: # Check and verify plugin and load variable overlay
pluginDir = os.path.join(baseDir, "plugins")
# Check if there is a .py at the end of PLUGIN_NAME variable
if PLUGIN_NAME.endswith(".py"):
PLUGIN_NAME = PLUGIN_NAME[:-3] # Remove .py extensiion
pluginPath = os.path.join(pluginDir, PLUGIN_NAME + ".py")
logging.info("pluginEnabled %s", pluginPath)
if not os.path.isdir(pluginDir):
logging.error("plugin Directory Not Found at %s", pluginDir)
logging.info("Rerun github curl install script to install plugins")
logging.info("https://github.com/pageauc/pi-timolo/wiki/")
logging.info("How-to-Install-or-Upgrade#quick-install")
logging.warning("%s %s Exiting Due to Error", PROG_NAME, PROG_VER)
sys.exit(1)
elif not os.path.exists(pluginPath):
logging.error("Plugin File Not Found %s", pluginPath)
logging.info("Check Spelling of PLUGIN_NAME Value in %s", configFilePath)
logging.info("------- Valid Names -------")
validPlugin = glob.glob(pluginDir + "/*py")
validPlugin.sort()
for entry in validPlugin:
pluginFile = os.path.basename(entry)
plugin = pluginFile.rsplit(".", 1)[0]
if not ((plugin == "__init__") or (plugin == "current")):
logging.info(" %s", plugin)
logging.info("------- End of List -------")
logging.info(" Note: PLUGIN_NAME Should Not have .py Ending.")
logging.info("or Rerun github curl install command. See github wiki")
logging.info("https://github.com/pageauc/speed-camera/wiki/")
logging.info("How-to-Install-or-Upgrade#quick-install")
logging.warning("%s %s Exiting Due to Error", PROG_NAME, PROG_VER)
sys.exit(1)
else:
pluginCurrent = os.path.join(pluginDir, "current.py")
try: # Copy image file to recent folder
logging.info("Copy %s to %s", pluginPath, pluginCurrent)
shutil.copy(pluginPath, pluginCurrent)
except OSError as err:
logging.error("Copy Failed %s to %s - %s", pluginPath, pluginCurrent, err)
logging.info("Check permissions, disk space, Etc.")
logging.warning("%s %s Exiting Due to Error", PROG_NAME, PROG_VER)
sys.exit(1)
# add plugin directory to program PATH
sys.path.insert(0, pluginDir)
try:
from plugins.current import *
except Exception as err_msg:
logging.warning("%s" % err_msg)
CAMERA_WIDTH, CAMERA_HEIGHT = IM_SIZE
# fix possible invalid values when resizing
if CV_WINDOW_BIGGER < 0.1:
CV_WINDOW_BIGGER = 0.1
if IM_BIGGER < 0.1:
IM_BIGGER = 0.1
# Calculate conversion from camera pixel width to actual speed.
CONV_KPH_2_MPH = 0.621371 # conversion from KPH to MPH
CONV_MM_PER_SEC_2_KPH = 0.0036 # conversion from MM/sec to KPH
px_to_kph_L2R = float(CAL_OBJ_MM_L2R / CAL_OBJ_PX_L2R * CONV_MM_PER_SEC_2_KPH)
px_to_kph_R2L = float(CAL_OBJ_MM_R2L / CAL_OBJ_PX_R2L * CONV_MM_PER_SEC_2_KPH)
if MO_SPEED_MPH_ON:
speed_units = "mph"
speed_conv_L2R = CONV_KPH_2_MPH * px_to_kph_L2R
speed_conv_R2L = CONV_KPH_2_MPH * px_to_kph_R2L
else:
speed_units = "kph"
speed_conv_L2R = px_to_kph_L2R
speed_conv_R2L = px_to_kph_R2L
# path to alignment camera image
align_filename = os.path.join(IM_RECENT_DIR_PATH, "align_cam.jpg")
speed_CSV_filepath = os.path.join(baseDir, baseFileName + ".csv")
AI_CSV_filepath = os.path.join(baseDir, "ai_pos_data.csv")
# ------------------------------------------------------------------------------
def show_config(filename):
'''
Display program configuration variable settings
read config file and print each decoded line
'''
print("")
logging.info("Reading settings per %s", configFilePath)
with open(filename, 'rb') as f:
for line in f:
print(line.decode().strip())
if PLUGIN_ENABLE_ON:
logging.warning("Some Settings Above will be changed by Plugin %s", PLUGIN_NAME)
# ------------------------------------------------------------------------------
def get_fps(start_time, frame_count):
"""
Calculate and display frames per second processing
"""
if frame_count >= 1000:
duration = float(time.time() - start_time)
FPS = float(frame_count / duration)
logging.info("%.2f fps Last %i Frames", FPS, frame_count)
frame_count = 0
start_time = time.time()
else:
frame_count += 1
return start_time, frame_count
# ------------------------------------------------------------------------------
def is_daytime(image, threshold):
"""
Calculate the mean pixel average value for a grayimage
used for determining if it is day or night. Bright enough to save image.
"""
day = False
grayimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
pix_ave = int(np.mean(grayimage))
if pix_ave >= threshold:
day = True
return day
# ------------------------------------------------------------------------------
def timer_is_on(sched_time):
"""
Based on schedule date setting see if current
datetime is past and return boolean
to indicate timer is off
"""
is_on = True
if sched_time <= datetime.datetime.now():
is_on = False # sched date/time has passed so start sequence
return is_on
# ------------------------------------------------------------------------------
def make_media_dirs():
"""
Create media default folders per config.py settings.
"""
cwd = os.getcwd()
html_path = "media/html"
if not os.path.isdir(IM_DIR_PATH):
logging.info("Creating Image Storage Folder %s", IM_DIR_PATH)
os.makedirs(IM_DIR_PATH)
os.chdir(IM_DIR_PATH)
os.chdir(cwd)
if IM_RECENT_MAX_FILES > 0:
if not os.path.isdir(IM_RECENT_DIR_PATH):
logging.info("Create Recent Folder %s", IM_RECENT_DIR_PATH)
try:
os.makedirs(IM_RECENT_DIR_PATH)
except OSError as err:
logging.error("Failed to Create Folder %s - %s", IM_RECENT_DIR_PATH, err)
if not os.path.isdir(search_dest_path):
logging.info("Creating Search Folder %s", search_dest_path)
os.makedirs(search_dest_path)
if not os.path.isdir(html_path):
logging.info("Creating html Folder %s", html_path)
os.makedirs(html_path)
if IM_SAVE_4AI_ON and not os.path.isdir(IM_SAVE_4AI_POS_DIR):
os.makedirs(IM_SAVE_4AI_POS_DIR)
if IM_SAVE_4AI_ON and not os.path.isdir(IM_SAVE_4AI_NEG_DIR):
os.makedirs(IM_SAVE_4AI_NEG_DIR)
os.chdir(cwd)
# ------------------------------------------------------------------------------
def show_settings():
"""
Display formatted program variable settings from config.py
"""
if LOG_VERBOSE_ON:
print(HORIZ_LINE)
print("Note: To Send Full Output to File Use command")
print("python -u ./%s | tee -a log.txt" % PROG_NAME)
print(
"Set log_data_to_file=True to Send speed_Data to CSV File %s.log"
% baseFileName
)
print(HORIZ_LINE)
print("")
print(
"Debug Messages .. LOG_VERBOSE_ON=%s LOG_FPS_ON=%s CALIBRATE_ON=%s"
% (LOG_VERBOSE_ON, LOG_FPS_ON, CALIBRATE_ON)
)
print(" MO_LOG_OUT_RANGE_ON=%s" % MO_LOG_OUT_RANGE_ON)
print(
"Plugins ......... PLUGIN_ENABLE_ON=%s PLUGIN_NAME=%s"
% (PLUGIN_ENABLE_ON, PLUGIN_NAME)
)
print(
"Calibration ..... CAL_OBJ_PX_L2R=%i px CAL_OBJ_MM_L2R=%i mm speed_conv_L2R=%.5f"
% (CAL_OBJ_PX_L2R, CAL_OBJ_MM_L2R, speed_conv_L2R)
)
print(
" CAL_OBJ_PX_R2L=%i px CAL_OBJ_MM_R2L=%i mm speed_conv_R2L=%.5f"
% (CAL_OBJ_PX_R2L, CAL_OBJ_MM_R2L, speed_conv_R2L)
)
if PLUGIN_ENABLE_ON:
print(" (Change Settings in %s)" % pluginPath)
else:
print(" (Change Settings in %s)" % configFilePath)
print(
"Logging ......... Log_data_to_CSV=%s log_filename=%s.csv (CSV format)"
% (LOG_DATA_TO_CSV, baseFileName)
)
print(
" LOG_TO_FILE_ON=%s LOG_FILE_PATH=%s"
% (LOG_TO_FILE_ON, LOG_FILE_PATH)
)
print(" SQLITE3 DB_PATH=%s DB_TABLE=%s" % (DB_PATH, DB_TABLE))
print(
"Speed Trigger ... Log only if MO_MAX_SPEED_OVER > %i %s"
% (MO_MAX_SPEED_OVER, speed_units)
)
print(
" and MO_TRACK_EVENT_COUNT >= %i consecutive motion events"
% MO_TRACK_EVENT_COUNT
)
print(
"Exclude Events .. If MO_MIN_X_DIFF_PX < %i or MO_MAX_X_DIFF_PX > %i px"
% (MO_MIN_X_DIFF_PX, MO_MAX_X_DIFF_PX)
)
print(
" If MO_CROP_Y_UPPER < %i or MO_CROP_Y_LOWER > %i px" % (MO_CROP_Y_UPPER, MO_CROP_Y_LOWER)
)
print(
" or MO_CROP_X_LEFT < %i or MO_CROP_X_RIGHT > %i px" % (MO_CROP_X_LEFT, MO_CROP_X_RIGHT)
)
print(
" If MO_MAX_SPEED_OVER < %i %s"
% (MO_MAX_SPEED_OVER, speed_units)
)
print(
" If MO_EVENT_TIMEOUT_SEC > %.2f seconds Start New Track"
% (MO_EVENT_TIMEOUT_SEC)
)
print(
" MO_TRACK_TIMEOUT_SEC=%.2f sec wait after Track Ends"
" (avoid retrack of same object)" % (MO_TRACK_TIMEOUT_SEC)
)
print(
"Speed Photo ..... Size=%ix%i px IM_BIGGER=%.1f"
" rotation=%i VFlip=%s HFlip=%s "
% (
image_width,
image_height,
IM_BIGGER,
IM_ROTATION,
IM_VFLIP,
IM_HFLIP,
)
)
print(
" IM_DIR_PATH=%s image_Prefix=%s"
% (IM_DIR_PATH, IM_PREFIX)
)
print(
" IM_FONT_SIZE_PX=%i px high IM_SHOW_TEXT_BOTTOM_ON=%s"
% (IM_FONT_SIZE_PX, IM_SHOW_TEXT_BOTTOM_ON)
)
print(
" IM_JPG_QUALITY=%s IM_JPG_OPTIMIZE_ON=%s"
% (IM_JPG_QUALITY, IM_JPG_OPTIMIZE_ON)
)
print(
"Motion Settings . Size=%ix%i px px_to_kph_L2R=%f px_to_kph_R2L=%f speed_units=%s"
% (CAMERA_WIDTH, CAMERA_HEIGHT, px_to_kph_L2R, px_to_kph_R2L, speed_units)
)
print(" CAM_LOCATION= %s" % CAM_LOCATION)
print(
"OpenCV Settings . MO_MIN_AREA_PX=%i sq-px BLUR_SIZE=%i"
" THRESHOLD_SENSITIVITY=%i CV_CIRCLE_SIZE_PX=%i px"
% (MO_MIN_AREA_PX, BLUR_SIZE, THRESHOLD_SENSITIVITY, CV_CIRCLE_SIZE_PX)
)
print(
" CV_WINDOW_BIGGER=%d GUI_WINDOW_ON=%s"
" (Display OpenCV Status Windows on GUI Desktop)"
% (CV_WINDOW_BIGGER, GUI_WINDOW_ON)
)
print(
" IM_FRAMERATE=%i fps video stream speed"
% IM_FRAMERATE
)
print(
"Sub-Directories . IM_SUBDIR_MAX_HOURS=%i (0=off)"
" IM_SUBDIR_MAX_FILES=%i (0=off)"
% (IM_SUBDIR_MAX_HOURS, IM_SUBDIR_MAX_FILES)
)
print(
" IM_RECENT_DIR_PATH=%s IM_RECENT_MAX_FILES=%i (0=off)"
% (IM_RECENT_DIR_PATH, IM_RECENT_MAX_FILES)
)
if SPACE_TIMER_HRS > 0: # Check if disk mgmnt is enabled
print(
"Disk Space ..... Enabled - Manage Target Free Disk Space."
" Delete Oldest %s Files if Needed" % (SPACE_FILE_EXT)
)
print(
" Check Every SPACE_TIMER_HRS=%i hr(s) (0=off)"
" Target SPACE_FREE_MB=%i MB min is 100 MB)"
% (SPACE_TIMER_HRS, SPACE_FREE_MB)
)
print(
" If Needed Delete Oldest SPACE_FILE_EXT=%s SPACE_MEDIA_DIR=%s"
% (SPACE_FILE_EXT, SPACE_MEDIA_DIR)
)
else:
print(
"Disk Space ..... Disabled - SPACE_TIMER_HRS=%i"
" Manage Target Free Disk Space. Delete Oldest %s Files"
% (SPACE_TIMER_HRS, SPACE_FILE_EXT)
)
print(
" SPACE_TIMER_HRS=%i (0=Off)"
" Target SPACE_FREE_MB=%i (min=100 MB)" % (SPACE_TIMER_HRS, SPACE_FREE_MB)
)
print("")
print(HORIZ_LINE)
return
# ------------------------------------------------------------------------------
def take_calibration_image(speed, filename, cal_image):
"""
Create a calibration image for determining value of IMG_VIEW_FT variable
Create calibration hash marks
"""
# If there is bad contrast with background you can change the hash
# colors to give more contrast. You need to change values below
# per values cvRed, cvBlue, cvWhite, cvBlack, cvGreen
hash_color = cvRed
motion_win_color = cvBlue
for i in range(10, image_width - 9, 10):
cv2.line(cal_image, (i, MO_CROP_Y_UPPER - 5), (i, MO_CROP_Y_UPPER + 30), hash_color, 1)
# This is motion window
cal_image = speed_image_add_lines(cal_image, motion_win_color)
print(
"----------------------------- Create Calibration Image "
"-----------------------------"
)
print("")
print(" Instructions for using %s image for camera calibration" % filename)
print("")
print(
" Note: If there is only one lane then L2R and R2L settings will be the same"
)
print(
" 1 - Use L2R and R2L with Same Size Reference Object, Eg. same vehicle for both directions."
)
print(
" 2 - For objects moving L2R Record CAL_OBJ_PX_L2R Value Using Red MO_CROP_Y_UPPER Hash Marks at every 10 px Current Setting is %i px"
% CAL_OBJ_PX_L2R
)
print(
" 3 - Record CAL_OBJ_MM_L2R of object. This is Actual length in mm of object above Current Setting is %i mm"
% CAL_OBJ_MM_L2R
)
print(
" If Recorded Speed %.1f %s is Too Low, Increasing CAL_OBJ_MM_L2R to Adjust or Visa-Versa"
% (speed, speed_units)
)
print(
"Repeat Calibration with same object moving R2L and update config.py R2L variables"
)
print("CAL_OBJ_MM_R2L and CAL_OBJ_PX_R2L accordingly")
if PLUGIN_ENABLE_ON:
print(" 4 - Edit %s File and Change Values for Above Variables." % pluginPath)
else:
print(
" 4 - Edit %s File and Change Values for the Above Variables."
% configFilePath
)
print(" 5 - Do a Speed Test to Confirm/Tune Settings. You May Need to Repeat.")
print(
" 6 - When Calibration is Finished, Set config.py Variable CALIBRATE_ON = False"
)
print(" Then Restart speed-cam.py and monitor activity.")
print("")
print(" WARNING: It is Advised to Use 320x240 Stream for Best Performance.")
print(" Higher Resolutions Need More OpenCV Processing")
print(" and May Reduce Data Accuracy and Reliability.")
print("")
print(" Calibration Image Saved To %s%s " % (baseDir, filename))
print(" View Calibration Image in Web Browser (Ensure webserver.py is started)")
print("")
print(
"---------------------- Press cntl-c to Quit Calibration Mode "
"-----------------------"
)
return cal_image
# ------------------------------------------------------------------------------
def subdir_latest(directory):
"""
Scan for directories and return most recent
"""
dirList = [
name
for name in os.listdir(directory)
if os.path.isdir(os.path.join(directory, name))
]
if len(dirList) > 0:
lastSubDir = sorted(dirList)[-1]
lastSubDir = os.path.join(directory, lastSubDir)
else:
lastSubDir = directory
return lastSubDir
# ------------------------------------------------------------------------------
def subdir_create(directory, prefix):
"""
Create media subdirectories base on required naming
"""
now = datetime.datetime.now()
# Specify folder naming
subDirName = "%s%d%02d%02d-%02d%02d" % (
prefix,
now.year,
now.month,
now.day,
now.hour,
now.minute,
)
subDirPath = os.path.join(directory, subDirName)
if not os.path.exists(subDirPath):
try:
os.makedirs(subDirPath)
except OSError as err:
logging.error(
"Cannot Create Dir %s - %s, using default location.", subDirPath, err
)
subDirPath = directory
else:
logging.info("Created %s", subDirPath)
else:
subDirPath = directory
return subDirPath
# ------------------------------------------------------------------------------
def delete_old_files(maxFiles, dirPath, prefix):
"""
Delete Oldest files gt or
equal to maxfiles that match filename prefix
"""
try:
fileList = sorted(
glob.glob(os.path.join(dirPath, prefix + "*")), key=os.path.getmtime
)
except OSError as err:
logging.error("Problem Reading Directory %s", dirPath)
logging.error("%s", err)
logging.error("Possibly symlink destination File Does Not Exist")
logging.error("To Fix - Try Deleting All Files in recent folder %s", dirPath)
else:
while len(fileList) >= maxFiles:
oldest = fileList[0]
oldestFile = oldest
try: # Remove oldest file in recent folder
fileList.remove(oldest)
os.remove(oldestFile)
except OSError as err:
logging.error("Cannot Remove %s - %s", oldestFile, err)
# ------------------------------------------------------------------------------
def subdir_check_max_files(directory, filesMax):
"""
Count number of files in a folder path
"""
fileList = glob.glob(directory + "/*")
count = len(fileList)
if count > filesMax:
makeNewDir = True
logging.info("Total Files in %s Exceeds %i ", directory, filesMax)
else:
makeNewDir = False
return makeNewDir
# ------------------------------------------------------------------------------
def subdir_check_max_hrs(directory, hrsMax, prefix):
"""
Rxtract the date-time from the directory name
"""
# Note to self need to add error checking
dirName = os.path.split(directory)[1] # split dir path and keep dirName
# remove prefix from dirName so just date-time left
dirStr = dirName.replace(prefix, "")
# convert string to datetime
dirDate = datetime.datetime.strptime(dirStr, "%Y%m%d-%H%M")
rightNow = datetime.datetime.now() # get datetime now
diff = rightNow - dirDate # get time difference between dates
days, seconds = diff.days, diff.seconds
dirAgeHours = days * 24 + seconds // 3600 # convert to hours
if dirAgeHours > hrsMax: # See if hours are exceeded
makeNewDir = True
logging.info("MaxHrs %i Exceeds %i for %s", dirAgeHours, hrsMax, directory)
else:
makeNewDir = False
return makeNewDir
# ------------------------------------------------------------------------------
def subdir_checks(maxHours, maxFiles, directory, prefix):
"""
Check if motion SubDir needs to be created
"""
if maxHours < 1 and maxFiles < 1: # No Checks required
# logging.info('No sub-folders Required in %s', directory)
subDirPath = directory
else:
subDirPath = subdir_latest(directory)
if subDirPath == directory: # No subDir Found
logging.info("No sub folders Found in %s", directory)
subDirPath = subdir_create(directory, prefix)
elif maxHours > 0 and maxFiles < 1: # Check MaxHours Folder Age Only
if subdir_check_max_hrs(subDirPath, maxHours, prefix):
subDirPath = subdir_create(directory, prefix)
elif maxHours < 1 and maxFiles > 0: # Check Max Files Only
if subdir_check_max_files(subDirPath, maxFiles):
subDirPath = subdir_create(directory, prefix)
elif maxHours > 0 and maxFiles > 0: # Check both Max Files and Age
if subdir_check_max_hrs(subDirPath, maxHours, prefix):
if subdir_check_max_files(subDirPath, maxFiles):
subDirPath = subdir_create(directory, prefix)
else:
logging.info("MaxFiles Not Exceeded in %s", subDirPath)
os.path.abspath(subDirPath)
return subDirPath
# ------------------------------------------------------------------------------
def files_to_delete(mediaDirPath, extension=IM_FORMAT_EXT):
"""
Return a list of files to be deleted
"""
return sorted(
(
os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(mediaDirPath)
for filename in filenames
if filename.endswith(extension)
),
key=lambda fn: os.stat(fn).st_mtime,
reverse=True,
)
# ------------------------------------------------------------------------------
def make_rel_symlink(sourceFilenamePath, symDestDir):
'''
Creates a relative symlink in the specified symDestDir
that points to the Target file via a relative rather than
absolute path. If a symlink already exists it will be replaced.
Warning message will be displayed if symlink path is a file
rather than an existing symlink.
'''
# Initialize target and symlink file paths
targetDirPath = os.path.dirname(sourceFilenamePath)
srcfilename = os.path.basename(sourceFilenamePath)
symDestFilePath = os.path.join(symDestDir, srcfilename)
# Check if symlink already exists and unlink if required.
if os.path.islink(symDestFilePath):
logging.info("Remove Existing Symlink at %s ", symDestFilePath)
os.unlink(symDestFilePath)
# Check if symlink path is a file rather than a symlink. Error out if required
if os.path.isfile(symDestFilePath):
logging.warning("Failed. File Exists at %s.", symDestFilePath)
return
# Initialize required entries for creating a relative symlink to target file
absTargetDirPath = os.path.abspath(targetDirPath)
absSymDirPath = os.path.abspath(symDestDir)
relativeDirPath = os.path.relpath(absTargetDirPath, absSymDirPath)
# Initialize relative symlink entries to target file.
symFilePath = os.path.join(relativeDirPath, srcfilename)
# logging.info("ln -s %s %s ", symFilePath, symDestFilePath)
os.symlink(symFilePath, symDestFilePath) # Create the symlink
# Check if symlink was created successfully
if os.path.islink(symDestFilePath):
logging.info("Saved at %s", symDestFilePath)
else:
logging.warning("Failed to Create Symlink at %s", symDestFilePath)
# ------------------------------------------------------------------------------
def save_recent(recentMax, recentDir, filepath, prefix):
"""
Create a symlink file in recent folder or file if non unix system
or symlink creation fails.
Delete Oldest symlink file if recentMax exceeded.
"""
if recentMax > 0:
delete_old_files(recentMax, os.path.abspath(recentDir), prefix)
try:
make_rel_symlink(filepath, recentDir)
except OSError as err:
logging.error("symlink Failed: %s", err)
try: # Copy image file to recent folder (if no support for symlinks)
shutil.copy(filepath, recentDir)
logging.info("Saved %s to %s", filepath, recentDir)
except OSError as err:
logging.error("Copy Failed %s to %s - %s", filepath, recentDir, err)
# ------------------------------------------------------------------------------
def free_disk_space_upto(freeMB, mediaDir, extension=IM_FORMAT_EXT):
"""
Walks mediaDir and deletes oldest files
until SPACE_FREE_MB is achieved Use with Caution
"""
mediaDirPath = os.path.abspath(mediaDir)
if os.path.isdir(mediaDirPath):
MB2Bytes = 1048576 # Conversion from MB to Bytes
targetFreeBytes = freeMB * MB2Bytes
fileList = files_to_delete(mediaDir, extension)
totFiles = len(fileList)
delcnt = 0
logging.info("Session Started")
while fileList:
statv = os.statvfs(mediaDirPath)
availFreeBytes = statv.f_bfree * statv.f_bsize
if availFreeBytes >= targetFreeBytes:
break
filePath = fileList.pop()
try:
os.remove(filePath)
except OSError as err:
logging.error("Del Failed %s", filePath)
logging.error("Error: %s", err)
else:
delcnt += 1
logging.info("Del %s", filePath)
logging.info(
"Target=%i MB Avail=%i MB Deleted %i of %i Files ",
targetFreeBytes / MB2Bytes,
availFreeBytes / MB2Bytes,
delcnt,
totFiles,
)
# Avoid deleting more than 1/4 of files at one time
if delcnt > totFiles / 4:
logging.warning("Max Deletions Reached %i of %i", delcnt, totFiles)
logging.warning(
"Deletions Restricted to 1/4 of total files per session."
)
break
logging.info("Session Ended")
else:
logging.error("Directory Not Found - %s", mediaDirPath)
# ------------------------------------------------------------------------------
def free_disk_space_check(lastSpaceCheck):
"""
Free disk space by deleting some older files
"""
if SPACE_TIMER_HRS > 0: # Check if disk free space timer hours is enabled
# See if it is time to do disk clean-up check
if (
datetime.datetime.now() - lastSpaceCheck
).total_seconds() > SPACE_TIMER_HRS * 3600:
lastSpaceCheck = datetime.datetime.now()
# Set freeSpaceMB to reasonable value if too low
if SPACE_FREE_MB < 100:
diskFreeMB = 100
else:
diskFreeMB = SPACE_FREE_MB
logging.info(
"SPACE_TIMER_HRS=%i diskFreeMB=%i SPACE_MEDIA_DIR=%s SPACE_FILE_EXT=%s",
SPACE_TIMER_HRS,
diskFreeMB,
SPACE_MEDIA_DIR,
SPACE_FILE_EXT,
)