-
Notifications
You must be signed in to change notification settings - Fork 0
/
PiVideoer.py
4279 lines (4055 loc) · 194 KB
/
PiVideoer.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/env python3
import time
import cv2
import numpy as np
import pygame
from pygame.locals import *
from PIL import Image
import os, subprocess, glob
import signal
import datetime
import shutil
import glob
from gpiozero import Button
from gpiozero import LED
from gpiozero import CPUTemperature
from gpiozero import PWMLED
import sys
import random
version = "1.14"
# set screen size
scr_width = 800
scr_height = 480
# use GPIO for external camera triggers and optional FAN.
# DISABLE Pi FAN CONTROL in Preferences > Performance to GPIO 14 !!
use_gpio = 0
# ext camera trigger output gpios (if use_gpio = 1)
s_focus = 16
s_trig = 12
# ext trigger input gpios (if use_gpio = 1)
e_trig1 = 21
e_trig2 = 20
# fan ctrl gpio (if use_gpio = 1) This is not the Pi5 active cooler !!
# DISABLE Pi FAN CONTROL in Preferences > Performance to GPIO 14 !!
fan = 14
fan_ctrl = 1 # 0 for OFF.
# save MP4 to SD / USB, 0 = SD Card, 1 = USB
movtousb = 0
# USB cameras
auto_detect = 1
# set default config parameters
v_crop = 80 # size of vertical detection window *
h_crop = 80 # size of horizontal detection window *
threshold = 20 # minm change in pixel luminance *
threshold2 = 255 # maxm change in pixel luminance *
detection = 10 # % of pixels detected to trigger, in % *
det_high = 100 # max % of pixels detected to trigger, in % *
fps = 25 # set camera fps *
mp4_fps = 25 # set MP4 fps *
mode = 1 # set camera mode ['off','normal','sport'] *
speed = 80000 # set manual shutter speed in mS x 1000 *
gain = 0 # set gain , 0 = AUTO *
brightness = 0 # set camera brightness *
contrast = 70 # set camera contrast *
Capture = 1 # 0 = off, 1 = ON *
preview = 0 # show detected changed pixels *
noframe = 0 # set to 1 for no window frame
awb = 1 # auto white balance, 1 = ON, 0 = OFF *
red = 3.5 # red balance *
blue = 1.5 # blue balance *
meter = 0 # metering *
ev = 0 # eV *
interval = 0 # wait between capturing Pictures *
v_length = 10000 # video length in mS *
ES = 1 # trigger external camera, 0 = OFF, 1 = SHORT, 2 = LONG *
denoise = 0 # denoise level *
quality = 90 # video quality *
sharpness = 14 # sharpness *
saturation = 12 # saturation *
SD_limit = 90 # max SD card filled in % before copy to USB if available or STOP *
auto_save = 1 # set to 1 to automatically copy to SD card
auto_time = 10 # time after which auto save actioned, 0 = OFF
ram_limit = 150 # MBytes, copy from RAM to SD card when reached *
fan_time = 10 # fan sampling time in seconds *
fan_low = 65 # fan OFF below this, 25% to 100% pwm above this *
fan_high = 78 # fan 100% pwm above this *
sd_hour = 22 # Shutdown Hour, 1 - 23, 0 will NOT SHUTDOWN *
vformat = 0 # SEE VWIDTHS/VHEIGHTS *
col_filter = 3 # 3 = FULL, SEE COL_FILTERS *
nr = 0 # Noise reduction *
pre_frames = fps * 2 # 2 x fps = 2 seconds *
scientific = 0 # scientific for HQ camera *
v3_f_mode = 0 # v3 camera focus mode *
v3_focus = 0 # v3 camera manual focus default *
dspeed = 10 # detection speed 1-100, 1 = slowest *
square = 0 # 0 = normal format , 1 = square format *
sqpos = .15 # square format position *
anno = 1 # annotate MP4s with date and time , 1 = yes, 0 = no *
SD_F_Act = 0 # Action on SD FULL, 0 = STOP, 1 = DELETE OLDEST VIDEO, 2 = COPY TO USB (if fitted) *
alp = 255 # alpha, used for stop animations, shows current and last frame *
m_alpha = 130 # MASK ALPHA *
photo_timer = 0.2 # time between photos (2 camera setup ONLY) *
mode2 = 1 # set camera2 mode ['off','normal','sport'] *
speed2 = 80000 # set manual shutter speed2 in mS x 1000 *
gain2 = 0 # set gain2 , 0 = AUTO *
brightness2 = 0 # set camera2 brightness *
contrast2 = 70 # set camera2 contrast *
ev2 = 0 # eV2 *
meter2 = 0 # meter2 *
sharpness2 = 14 # sharpness2
saturation2 = 12 # saturation2
framerate2 = 25 # framerate2 *
# * adjustable whilst running
# initialise parameters
camera = 0
synced = 0
show = 0
reboot = 0
stopped = 0
record = 0
timer = 0
zoom = 0
trace = 0
timer10 = 0
col_filterp = 0
config_file = "PiVideoconfig101.txt"
a = int(scr_width/3)
b = int(scr_height/2)
fcount = 0
dc = 0
q = 0
of = 0
txtvids = []
en_photo = 0
restart2 = 0
timer2 = time.monotonic()
res2 = 0
fcount = 0
max_fcount = 10
gcount = 0
fstep = 20
old_foc = 0
min_foc = 15
# Camera max exposure (Note v1 is currently 1 second not the raspistill 6 seconds)
# whatever value set it MUST be in shutters list !!
max_v1 = 1
max_v2 = 11
max_v3 = 112
max_hq = 650
max_16mp = 200
max_64mp = 435
max_gs = 15
# setup directories
Home_Files = []
Home_Files.append(os.getlogin())
pic = "Pictures"
pic_dir = "/home/" + Home_Files[0]+ "/" + pic + "/"
cameras = ['Unknown','Pi v1','Pi v2','Pi v3','Pi HQ','Arducam 16MP','Arducam 64MP','Pi GS']
camids = ['','ov5647','imx219','imx708','imx477','imx519','arduc','imx296']
max_gains = [64, 255, 40, 64, 88, 64, 64, 64]
max_shutters = [0, max_v1, max_v2, max_v3, max_hq,max_16mp,max_64mp, max_gs]
mags = [64, 255, 40, 64, 88, 64, 64, 64]
modes = ['off','normal','sport']
meters = ['centre','spot','average']
awbs = ['off','auto','incandescent','tungsten','fluorescent','indoor','daylight','cloudy']
denoises = ['off','cdn_off','cdn_fast','cdn_hq']
vwidths = []
vheights = []
col_filters = ['RED','GREEN','BLUE','FULL']
noise_filters = ['OFF','LOW','HIGH']
v3_f_modes = ['auto','manual','continuous']
#check Pi model.
Pi = 0
if os.path.exists ('/run/shm/md.txt'):
os.remove("/run/shm/md.txt")
os.system("cat /proc/cpuinfo >> /run/shm/md.txt")
with open("/run/shm/md.txt", "r") as file:
line = file.readline()
while line:
line = file.readline()
if line[0:5] == "Model":
model = line
mod = model.split(" ")
if mod[3] == "5":
Pi = 5
# setup gpio if enabled
if use_gpio == 1:
# external output triggers
led_s_trig = LED(s_trig)
led_s_focus = LED(s_focus)
led_s_trig.off()
led_s_focus.off()
# optional fan control
if fan_ctrl == 1:
led_fan = PWMLED(fan)
led_fan.value = 0
# external input triggers
button_e_trig1 = Button(e_trig1,pull_up=False)
button_e_trig2 = Button(e_trig2,pull_up=False)
# check Vid_configXX.txt exists, if not then write default values
if not os.path.exists(config_file):
defaults = [h_crop,threshold,fps,mode,speed,gain,brightness,contrast,SD_limit,preview,awb,detection,int(red*10),int(blue*10),
interval,v_crop,v_length,ev,meter,ES,a,b,sharpness,saturation,denoise,fan_low,fan_high,det_high,quality,
fan_time,sd_hour,vformat,threshold2,col_filter,nr,pre_frames,auto_time,ram_limit,v3_f_mode,v3_focus,square,int(sqpos*100),
mp4_fps,anno,SD_F_Act,dspeed,int(photo_timer*10),camera,mode2,speed2,gain2,brightness2,contrast2,ev2,meter2,sharpness2,saturation2,
framerate2]
with open(config_file, 'w') as f:
for item in defaults:
f.write("%s\n" % item)
# read config file
config = []
with open(config_file, "r") as file:
line = file.readline()
while line:
config.append(line.strip())
line = file.readline()
config = list(map(int,config))
h_crop = config[0]
threshold = config[1]
fps = config[2]
mode = config[3]
speed = config[4]
gain = config[5]
brightness = config[6]
contrast = config[7]
SD_limit = config[8]
preview = config[9]
awb = config[10]
detection = config[11]
red = config[12]/10
blue = config[13]/10
interval = config[14]
v_crop = config[15]
v_length = config[16]
ev = config[17]
meter = config[18]
ES = config[19]
a = config[20]
b = config[21]
sharpness = config[22]
saturation = config[23]
denoise = config[24]
fan_low = config[25]
fan_high = config[26]
det_high = config[27]
quality = config[28]
fan_time = config[29]
sd_hour = config[30]
vformat = config[31]
threshold2 = config[32]
col_filter = config[33]
nr = config[34]
pre_frames = config[35]
auto_time = config[36]
ram_limit = config[37]
#v3_f_mode = config[38]
#v3_focus = config[39]
square = config[40]
sqpos = config[41]/100
mp4_fps = config[42]
anno = config[43]
SD_F_Act = config[44]
dspeed = config[45]
photo_timer = config[46]/10
#camera = config[47]
mode2 = config[48]
speed2 = config[49]
gain2 = config[50]
brightness2 = config[51]
contrast2 = config[52]
ev2 = config[53]
meter2 = config[54]
sharpness2 = config[55]
saturation2 = config[56]
framerate2 = config[57]
bw = int(scr_width/8)
cwidth = scr_width - bw
cheight = scr_height
old_vf = vformat
focus = 0
def Camera_Version():
global old_vf,bw,Pi_Cam,cam1,cam2,camera,camids,max_camera,same_cams,max_gain,max_vf,max_vfs,a,b,a2,b2,h_crop,v_crop,h_crop2,v_crop2,cap_width,cap_height,vformat,xheight,cwidth,vwidths,vheights,xwidth,scr_width,scr_height # DETERMINE NUMBER OF CAMERAS (FOR Pi5)
if os.path.exists('libcams.txt'):
os.rename('libcams.txt', 'oldlibcams.txt')
os.system("rpicam-vid --list-cameras >> libcams.txt")
time.sleep(0.5)
# read libcams.txt file
camstxt = []
with open("libcams.txt", "r") as file:
line = file.readline()
while line:
camstxt.append(line.strip())
line = file.readline()
max_camera = 0
same_cams = 0
cam1 = "1"
cam2 = "2"
vwidths = []
vheights = []
cwidth = scr_width - bw
cheight = scr_height
for x in range(0,len(camstxt)):
# Determine if both cameras are the same model
if camstxt[x][0:4] == "0 : ":
cam1 = camstxt[x][4:10]
elif camstxt[x][0:4] == "1 : ":
cam2 = camstxt[x][4:10]
elif cam1 != "1" and cam2 == "2" and camera == 0:
forms = camstxt[x].split(" ")
for q in range(0,len(forms)):
if "x" in forms[q] and "/" not in forms[q]:
qwidth,qheight = forms[q].split("x")
vwidths.append(int(qwidth))
vheights.append(int(qheight))
elif cam1 != "1" and cam2 != "2" and camera == 1:
forms = camstxt[x].split(" ")
for q in range(0,len(forms)):
if "x" in forms[q] and "/" not in forms[q]:
qwidth,qheight = forms[q].split("x")
vwidths.append(int(qwidth))
vheights.append(int(qheight))
# Determine MAXIMUM number of cameras available
if camstxt[x][0:4] == "3 : " and max_camera < 3:
max_camera = 3
elif camstxt[x][0:4] == "2 : " and max_camera < 2:
max_camera = 2
elif camstxt[x][0:4] == "1 : " and max_camera < 1:
max_camera = 1
if max_camera == 1 and cam1 == cam2:
same_cams = 1
Pi_Cam = -1
for x in range(0,len(camids)):
if camera == 0:
if cam1 == camids[x]:
Pi_Cam = x
elif camera == 1:
if cam2 == camids[x]:
Pi_Cam = x
if Pi_Cam != 7:
vwidths.insert(0, 1280)
vheights.insert(0,720)
vwidths.insert(0,1920)
vheights.insert(0,1080)
#print(vwidths,vheights)
max_gain = max_gains[Pi_Cam]
if vformat > len(vwidths) - 1 or camera == 1:
vformat = len(vwidths) - 1
old_vf = vformat
if camera == 0:
vformat = old_vf
cap_width = vwidths[vformat]
cap_height = vheights[vformat]
xheight = int(cwidth * (cap_height/cap_width))
if xheight > scr_height:
xheight = scr_height
cwidth = int(xheight * (cap_width/cap_height))
if square == 0:
xwidth = cwidth
else:
xwidth = xheight
if a > xwidth - v_crop:
a = int(xwidth/2)
if b > xheight - h_crop:
b = int(xheight/2)
a2 = int(a * (cap_width/cwidth))
b2 = int(b * (cap_height/xheight))
h_crop2 = int(h_crop * (cap_width/cwidth))
v_crop2 = int(v_crop * (cap_height/xheight))
if Pi_Cam == -1:
print("No Camera Found")
pygame.display.quit()
sys.exit()
Camera_Version()
print(Pi_Cam,cam1,cam2)
#set screen image width
if square == 1:
apos = 100
else:
apos = int(cap_width/4)
bh = int(scr_height/12)
font_size = int(min(bh, bw)/3)
start_up = time.monotonic()
col_timer = 0
pygame.init()
# find usb cameras
v1 = -1
v2 = -1
v3 = -1
v4 = -1
for x in range (0,42):
txt = "v4l2-ctl -d " + str(x) + " --list-ctrls > cam_ctrls.txt"
os.system(txt)
ctrls = []
with open("cam_ctrls.txt", "r") as file:
line = file.readline()
while line:
ctrls.append(line)
line = file.readline()
if 'User Controls\n' in ctrls and ('Camera Controls\n' in ctrls or ' band_stop_filter 0x00980921 (bool) : default=0 value=0\n' in ctrls):
if v1 == -1:
v1 = x
elif v2 == -1:
v2 = x
elif v3 == -1:
v3 = x
elif v4 == -1:
v4 = x
def camera_format(usb):
# find formats, and set USB still width and height
global width,height,preview_width,preview_height,still_width,still_height
txt = "v4l2-ctl -d " + str(usb) + " --list-formats-ext > cam_fmts.txt"
os.system(txt)
w = 0
h = 0
with open("cam_fmts.txt", "r") as file:
line = file.readline()
while line:
line = file.readline()
count = line.count(":")
if count == 1:
a,b = line.split(":")
if a[len(a)-4:len(a)] == "Size":
c,d = b.split("x")
e,f,g = c.split(" ")
if int(d) > h:
h = int(d)
if int(g) > w:
w = int(g)
if w != 0 and h!= 0:
width = w
height = h
print ("USB " + str(usb) + " Still Format set: " ,width," x" ,height)
# start USB cameras
if v1 != -1:
if auto_detect == 1:
camera_format(v1)
vid1 = cv2.VideoCapture(v1)
vid1.set(cv2.CAP_PROP_FRAME_WIDTH, width)
vid1.set(cv2.CAP_PROP_FRAME_HEIGHT,height)
if v2 != -1:
if auto_detect == 1:
camera_format(v2)
vid2 = cv2.VideoCapture(v2)
vid2.set(cv2.CAP_PROP_FRAME_WIDTH, width)
vid2.set(cv2.CAP_PROP_FRAME_HEIGHT,height)
if v3 != -1:
if auto_detect == 1:
camera_format(v3)
vid3 = cv2.VideoCapture(v3)
vid3.set(cv2.CAP_PROP_FRAME_WIDTH, width)
vid3.set(cv2.CAP_PROP_FRAME_HEIGHT,height)
if v4 != -1:
if auto_detect == 1:
camera_format(v4)
vid4 = cv2.VideoCapture(v4)
vid4.set(cv2.CAP_PROP_FRAME_WIDTH, width)
vid4.set(cv2.CAP_PROP_FRAME_HEIGHT,height)
print(v1,v2,v3,v4)
fxx = 0
fxy = 0
fxz = 1
USB_storage = 100
# find username
h_user = "/home/" + os.getlogin( )
m_user = "/media/" + os.getlogin( )
l_len = len(h_user)
if os.path.exists('/usr/share/rpicam/ipa/rpi/vc4/imx477_scientific.json') and Pi_Cam == 4:
scientif = 1
else:
scientif = 0
if not os.path.exists(h_user + '/CMask.bmp'):
pygame.init()
bredColor = pygame.Color(100,100,100)
mwidth = 200
mheight = 200
windowSurfaceObj = pygame.display.set_mode((mwidth, mheight), pygame.NOFRAME, 24)
pygame.draw.rect(windowSurfaceObj,bredColor,Rect(0,0,mwidth,mheight))
pygame.display.update()
pygame.image.save(windowSurfaceObj,h_user + '/CMask.bmp')
pygame.display.quit()
def MaskChange(): # used for masked window resizing
global v_crop2,h_crop2
mask = cv2.imread(h_user + '/CMask.bmp')
mask = cv2.resize(mask, dsize=(v_crop2 * 2, h_crop2 * 2), interpolation=cv2.INTER_CUBIC)
mask = cv2.cvtColor(mask,cv2.COLOR_RGB2GRAY)
mask = mask.astype(np.int16)
mask[mask >= 1] = 1
change = 1
return (mask,change)
mask,change = MaskChange()
if os.path.exists('mylist.txt'):
os.remove('mylist.txt')
# determine /dev/v4l-subdevX for Pi v3 and Arducam 16/64MP cameras
foc_sub3 = -1
foc_sub5 = -1
for x in range(0,10):
if os.path.exists("ctrls.txt"):
os.remove("ctrls.txt")
os.system("v4l2-ctl -d /dev/v4l-subdev" + str(x) + " --list-ctrls >> ctrls.txt")
time.sleep(0.25)
ctrlstxt = []
with open("ctrls.txt", "r") as file:
line = file.readline()
while line:
ctrlstxt.append(line.strip())
line = file.readline()
for j in range(0,len(ctrlstxt)):
if ctrlstxt[j][0:51] == "focus_absolute 0x009a090a (int) : min=0 max=4095":
foc_sub5 = x
if ctrlstxt[j][0:51] == "focus_absolute 0x009a090a (int) : min=0 max=1023":
foc_sub3 = x
# start Pi Camera subprocess
def Camera0_start(wx,hx,zoom):
global camera,sqpos,square,scientif,fxx,fxy,fxz,Pi_Cam,v3_f_modes,v3_f_mode,scientific,SD_storage,trace,p,red,blue,contrast,brightness,gain,speed,modes,mode,ev,ES,cap_width,cap_height,pre_frames,awbs,awb,meters,meter,sharpness,saturation,denoise,cwidth,xheight
if trace == 1:
print ("Step 1 START SUB PROC")
# clear ram
zpics = glob.glob('/run/shm/test*.jpg')
for tt in range(0,len(zpics)):
os.remove(zpics[tt])
st = os.statvfs("/run/shm/")
freeram = (st.f_bavail * st.f_frsize)/1100000
ss = str(int(sfreeram)) + "MB - " + str(int(SD_storage)) + "%"
if camera == 0:
rpistr = "rpicam-vid --camera " + str(camera) + " -t 0 --segment 1 --codec mjpeg -q " + str(quality)
rpistr += " -n -o /run/shm/test%06d.jpg --contrast " + str(contrast/100) + " --brightness " + str(brightness/100)
if square == 1:
rpistr += " --width " + str(hx) + " --height " + str(hx)
else:
rpistr += " --width " + str(wx) + " --height " + str(hx)
if awb > 0:
rpistr += " --awb " + awbs[awb]
else:
rpistr += " --awbgains " + str(red) + "," + str(blue)
if mode == 0:
rpistr +=" --shutter " + str(speed) + " --framerate " + str(int((1/speed)*1000000))
else:
rpistr +=" --exposure " + str(modes[mode]) + " --framerate " + str(fps)
rpistr += " --ev " + str(ev) + " --gain " + str(gain)
rpistr += " --metering " + meters[meter]
rpistr += " --saturation " + str(saturation/10)
rpistr += " --sharpness " + str(sharpness/10)
rpistr += " --denoise " + denoises[denoise]
if square == 1:
if Pi_Cam == 7 or Pi_Cam == 3:
rpistr += " --roi " + str(sqpos) + ",0," + str(hx/wx) + ",1"
elif Pi_Cam == 2:
rpistr += " --roi " + str(sqpos) + ",0.28,0.325,0.44"
else:
rpistr += " --roi " + str(sqpos) + ",0.14,0.5625,0.7"
if Pi_Cam == 3 and v3_f_mode > 0 :
rpistr += " --autofocus-mode " + v3_f_modes[v3_f_mode]
if v3_f_mode == 1:
rpistr += " --lens-position " + str(v3_focus/100)
if Pi_Cam == 3 and zoom == 0:
rpistr += " --autofocus-window " + str(fxx) + "," + str(fxy) + "," + str(fxz) + "," + str(fxz)
if scientific == 1 and Pi_cam == 4:
rpistr += " --tuning-file /usr/share/libcamera/ipa/rpi/vc4/imx477_scientific.json"
if (Pi_Cam == 5 or Pi_Cam == 6) and v3_f_mode == 1 and Pi == 5:
if os.path.exists('/usr/share/libcamera/ipa/rpi/pisp/imx519mf.json'):
rpistr += " --tuning-file /usr/share/libcamera/ipa/rpi/pisp/imx519mf.json"
if camera == 1:
rpistr = 'rpicam-vid --camera 1 -n -t 0 --segment 1 --codec mjpeg -o /run/shm/test%06d.jpg --contrast ' + str(contrast2/100) + " --brightness " + str(brightness2/100)
if mode2 == 0:
rpistr +=" --shutter " + str(speed2) + " --framerate " + str(framerate2)
else:
rpistr +=" --exposure " + str(modes[mode2]) + " --framerate " + str(framerate2)
rpistr += " --ev " + str(ev2) + " --gain " + str(gain2)
rpistr += " --width " + str(wx) + " --height " + str(hx)
#print (rpistr)
p = subprocess.Popen(rpistr, shell=True, preexec_fn=os.setsid)
st = time.monotonic()
poll = p.poll()
if poll != None and time.monotonic() - st < 5:
poll = p.poll()
if poll != None:
print ("Failed to start sub-process")
# check for usb_stick
USB_Files = []
USB_Files = (os.listdir(m_user + "/"))
print(USB_Files)
if len(USB_Files) > 0:
usedusb = os.statvfs(m_user + "/" + USB_Files[0] + "/")
USB_storage = ((1 - (usedusb.f_bavail / usedusb.f_blocks)) * 100)
if not os.path.exists(m_user + "/'" + USB_Files[0] + "'/Videos/") :
os.system('mkdir ' + m_user + "/'" + USB_Files[0] + "'/Videos/")
if not os.path.exists(m_user + "/'" + USB_Files[0] + "'/Pictures/") :
os.system('mkdir ' + m_user + "/'" + USB_Files[0] + "'/Pictures/")
old_cap = Capture
# read list of existing Video Files
outvids = []
z = ""
y = ""
frames = 0
ram_frames = 0
sframe = -1
eframe = -1
trig = 1
# SD card
Sideos = glob.glob(h_user + '/Pictures/*.jpg')
Sideos.sort()
for x in range(0,len(Sideos)):
Tideos = Sideos[x].split("/")
if Tideos[len(Tideos) - 1][:-10] != z:
z = Tideos[len(Tideos) - 1][:-10]
outvids.append(z)
frames +=1
# read list of existing Photo Files
photos = []
photos = glob.glob(h_user + '/Pictures/CAM1_*.jpg')
photos.sort()
# USB stick
USB_Files = []
USB_Files = (os.listdir(m_user + "/"))
if len(USB_Files) > 0:
Sideos = glob.glob(m_user + "/'" + USB_Files[0] + "'/Pictures/*.jpg")
Sideos.sort()
for x in range(0,len(Sideos)):
Tideos = Sideos[x].split("/")
if Tideos[len(Tideos) - 1][:-10] != z:
z = Tideos[len(Tideos) - 1][:-10]
outvids.append(z)
frames +=1
vf = str(ram_frames) + " - " + str(frames)
if Pi == 5 and cam2 != "2":
vf = vf + " - " + str(len(photos))
# read list of existing MP4 files
Mideos = glob.glob(h_user + '/Videos/*.mp4')
restart = 0
menu = -1
zoom = 0
# get RAM free space
st = os.statvfs("/run/shm/")
sfreeram = (st.f_bavail * st.f_frsize)/1100000
# check if clock synchronised
os.system("timedatectl >> sync.txt")
# read sync.txt file
try:
sync = []
with open("sync.txt", "r") as file:
line = file.readline()
while line:
sync.append(line.strip())
line = file.readline()
if sync[4] == "System clock synchronized: yes":
synced = 1
else:
synced = 0
except:
pass
# setup pygame window
if noframe == 0:
windowSurfaceObj = pygame.display.set_mode((scr_width,scr_height), 0, 24)
else:
windowSurfaceObj = pygame.display.set_mode((scr_width,scr_height), pygame.NOFRAME, 24)
pygame.display.set_caption('Action ' + cameras[Pi_Cam])
global greyColor, redColor, greenColor, blueColor, dgryColor, lgryColor, blackColor, whiteColor, purpleColor, yellowColor
bredColor = pygame.Color(255, 0, 0)
lgryColor = pygame.Color(192, 192, 192)
blackColor = pygame.Color( 0, 0, 0)
whiteColor = pygame.Color(250, 250, 250)
greyColor = pygame.Color(128, 128, 128)
dgryColor = pygame.Color( 64, 64, 64)
greenColor = pygame.Color( 0, 255, 0)
purpleColor = pygame.Color(255, 0, 255)
yellowColor = pygame.Color(255, 255, 0)
blueColor = pygame.Color( 0, 0, 255)
redColor = pygame.Color(200, 0, 0)
def button(col,row, bColor):
colors = [greyColor, dgryColor, whiteColor, redColor, greenColor,yellowColor]
Color = colors[bColor]
bx = scr_width - ((1-col) * bw) + 2
by = row * bh
pygame.draw.rect(windowSurfaceObj,Color,Rect(bx+1,by,bw-2,bh))
pygame.draw.line(windowSurfaceObj,whiteColor,(bx+1,by),(bx+bw,by))
pygame.draw.line(windowSurfaceObj,greyColor,(bx+bw-1,by),(bx+bw-1,by+bh))
pygame.draw.line(windowSurfaceObj,whiteColor,(bx,by),(bx,by+bh-1))
pygame.draw.line(windowSurfaceObj,dgryColor,(bx+1,by+bh-1),(bx+bw-1,by+bh-1))
pygame.display.update(bx, by, bw-1, bh)
return
def text(col,row,fColor,top,upd,msg,fsize,bcolor):
global font_size, fontObj, bh, bw, cwidth
if os.path.exists ('/usr/share/fonts/truetype/freefont/FreeSerif.ttf'):
fontObj = pygame.font.Font('/usr/share/fonts/truetype/freefont/FreeSerif.ttf', int(fsize))
else:
fontObj = pygame.font.Font(None, int(fsize))
colors = [dgryColor, greenColor, yellowColor, redColor, greenColor, blueColor, whiteColor, greyColor, blackColor, purpleColor]
Color = colors[fColor]
bColor = colors[bcolor]
bx = scr_width - ((1-col) * bw)
by = row * bh
msgSurfaceObj = fontObj.render(msg, False, Color)
msgRectobj = msgSurfaceObj.get_rect()
if top == 0:
pygame.draw.rect(windowSurfaceObj,bColor,Rect(bx+3,by+1,bw-2,int(bh/2)))
msgRectobj.topleft = (bx + 7, by + 3)
elif msg == "START - END" or msg == "<< < > >>":
pygame.draw.rect(windowSurfaceObj,bColor,Rect(bx+int(bw/4),by+int(bh/2),int(bw/1.5),int(bh/2)-1))
msgRectobj.topleft = (bx+7, by + int(bh/2))
else:
pygame.draw.rect(windowSurfaceObj,bColor,Rect(bx+int(bw/4),by+int(bh/2),int(bw/1.5),int(bh/2)-1))
msgRectobj.topleft = (bx+int(bw/4), by + int(bh/2))
windowSurfaceObj.blit(msgSurfaceObj, msgRectobj)
if upd == 1:
pygame.display.update(bx, by, bw, bh)
def main_menu():
global ram_frames,frames,menu,sd_hour,pf,vf,synced,Capture,show,zoom,preview,scr_height,cwidth,photos
menu = -1
show = 0
preview = 0
Capture = old_cap
zoom = 0
for d in range(0,11):
button(0,d,0)
button(0,1,3)
zzpics = glob.glob(h_user + '/Pictures/*99999.jpg')
rpics = glob.glob('/run/shm/*99999.jpg')
frames = 0
ram_frames = 0
for x in range(0,len(rpics)):
zzpics.append(rpics[x])
USB_Files = (os.listdir(m_user))
if len(USB_Files) > 0:
upics = glob.glob(m_user + "/'" + USB_Files[0] + "'/Pictures/*99999.jpg")
for x in range(0,len(upics)):
zzpics.append(upics[x])
zzpics.sort()
z = ""
y = ""
for x in range(0,len(zzpics)):
Tideos = zzpics[x].split("/")
if len(Tideos) >= 5:
if Tideos[len(Tideos) - 1][:-10] != z:
z = Tideos[len(Tideos) - 1][:-10]
outvids.append(z)
frames +=1
else:
if Tideos[len(Tideos) - 1][:-10] != y:
y = Tideos[len(Tideos) - 1][:-10]
outvids.append(y)
ram_frames +=1
photos = glob.glob(h_user + '/Pictures/CAM1_*.jpg')
photos.sort()
if Capture == 0 and menu == -1:
button(0,0,0)
text(0,0,0,0,1,"CAPTURE",16,7)
vf = str(ram_frames) + " - " + str(frames)
if Pi == 5 and cam2 != "2":
vf = vf + " - " + str(len(photos))
text(0,0,3,1,1,vf,14,7)
elif menu == -1:
button(0,0,4)
text(0,0,6,0,1,"CAPTURE",16,4)
vf = str(ram_frames) + " - " + str(frames)
if Pi == 5 and cam2 != "2":
vf = vf + " - " + str(len(photos))
text(0,0,3,1,1,vf,14,4)
text(0,1,6,0,1,"RECORD",16,3)
text(0,2,1,0,1,"DETECTION",14,7)
text(0,2,1,1,1,"Settings",14,7)
text(0,3,1,0,1,"CAMERA",14,7)
text(0,3,1,1,1,"Settings 1",14,7)
text(0,4,1,0,1,"CAMERA",14,7)
text(0,4,1,1,1,"Settings 2",14,7)
text(0,5,1,0,1,"CAMERA",14,7)
text(0,5,1,1,1,"Settings 3",14,7)
text(0,7,1,0,1,"OTHER",14,7)
text(0,7,1,1,1,"Settings ",14,7)
if ((ram_frames > 0 or frames > 0 or len(photos) > 0) and menu == -1):
text(0,6,1,0,1,"SHOW,EDIT or",13,7)
text(0,6,1,1,1,"DELETE",13,7)
else:
text(0,6,0,0,1,"SHOW,EDIT or",13,7)
text(0,6,0,1,1,"DELETE",13,7)
if ram_frames > 0 or frames > 0:
text(0,8,1,0,1,"MAKE",14,7)
text(0,8,1,1,1,"MP4",14,7)
else:
text(0,8,0,0,1,"MAKE",14,7)
text(0,8,0,1,1,"MP4",14,7)
if Pi == 5 and cam2 != "2":
text(0,9,1,0,1,"2nd Camera",14,7)
text(0,9,1,1,1,"Settings",14,7)
text(0,10,3,0,1,"EXIT",16,7)
st = os.statvfs("/run/shm/")
freeram = (st.f_bavail * st.f_frsize)/1100000
free = (os.statvfs('/'))
SD_storage = ((1 - (free.f_bavail / free.f_blocks)) * 100)
ss = str(int(freeram)) + "MB - " + str(int(SD_storage)) + "%"
if record == 0:
text(0,1,6,1,1,ss,12,3)
else:
text(0,1,6,1,1,ss,12,0)
pygame.draw.rect(windowSurfaceObj,(0,0,0),Rect(0,0,scr_width - bw,scr_height))
#pygame.display.update()
# clear ram
zpics = glob.glob('/run/shm/*.jpg')
for tt in range(0,len(zpics)):
os.remove(zpics[tt])
main_menu()
oldimg = []
show = 0
vidjr = 0
Videos = []
last = time.monotonic()
fan_timer = time.monotonic()
# check sd card space
free = (os.statvfs('/'))
SD_storage = ((1 - (free.f_bavail / free.f_blocks)) * 100)
ss = str(int(sfreeram)) + "MB - " + str(int(SD_storage)) + "%"
# start Pi Camera0 subprocess
Camera0_start(cap_width,cap_height,zoom)
if cam2 != "2":
# start 2nd Pi camera
now = datetime.datetime.now()
timestamp = now.strftime("%y%m%d%H%M%S")
fname = pic_dir + 'CAM1_' + str(timestamp) + '_%04d.jpg'
rpistr2 = 'rpicam-still --camera 1 -s -n -t 0 -e jpg -o ' + fname + ' --contrast ' + str(contrast2/100) + " --brightness " + str(brightness2/100)
if mode2 == 0:
rpistr2 +=" --shutter " + str(speed2)
else:
rpistr2 +=" --exposure " + str(modes[mode2])
rpistr2 += " --ev " + str(ev2) + " --gain " + str(gain2)
rpistr2 += " --metering " + meters[meter2]
rpistr2 += " --sharpness " + str(sharpness2/10)
#print(rpistr2)
s = subprocess.Popen(rpistr2, shell=True, preexec_fn=os.setsid)
poll = s.poll()
while poll != None:
print("waiting...")
poll = s.poll()
cpu_temp = str(CPUTemperature()).split("=")
temp = float(str(cpu_temp[1])[:-1])
old_capture = Capture
while True:
time.sleep(1/dspeed)
if Pi == 5 and menu == 4:
text(0,0,2,0,1,"CPU Temp/FAN",13,7)
if os.path.exists ('fantxt.txt'):
os.remove("fantxt.txt")
os.system("cat /sys/devices/platform/cooling_fan/hwmon/*/fan1_input >> fantxt.txt")
time.sleep(0.25)
with open("fantxt.txt", "r") as file:
line = file.readline()
if line == "":
line = 0
text(0,0,3,1,1,str(int(temp)) + " / " + str(int(line)),14,7)
elif menu == 4:
text(0,0,2,0,1,"CPU Temp",14,7)
text(0,0,3,1,1,str(int(temp)),14,7)
# fan (NOT Pi5 active cooler) and shutdown ctrl
if time.monotonic() - fan_timer > fan_time:
if trace == 1:
print ("Step FAN TIME")
try:
if os.path.exists("sync.txt"):
os.rename('sync.txt', 'oldsync.txt')
os.system("timedatectl >> sync.txt")
# read sync.txt file
sync = []
with open("sync.txt", "r") as file:
line = file.readline()
while line:
sync.append(line.strip())
line = file.readline()
if sync[4] == "System clock synchronized: yes":
synced = 1
if menu == 7:
text(0,9,3,1,1,str(sd_hour) + ":00",14,7)
else:
synced = 0
if menu == 7:
text(0,9,0,1,1,str(sd_hour)+":00",14,7)
except:
pass
# check current hour
now = datetime.datetime.now()
hour = int(now.strftime("%H"))
# shutdown if shutdown hour reached and clocked synced
if hour > sd_hour - 1 and sd_hour != 0 and time.monotonic() - start_up > 600 and synced == 1:
# EXIT and SHUTDOWN
if trace == 1:
print ("Step 13 TIMED EXIT")
# move any videos to SD Card
if ram_frames > 0:
if menu == -1 :
button(0,0,1)
text(0,0,5,0,1,"CAPTURE",16,0)
vf = str(ram_frames) + " - " + str(frames)
if Pi == 5 and cam2 != "2":
vf = vf + " - " + str(len(photos))
text(0,0,3,1,1,vf,14,4)
zpics = glob.glob('/run/shm/2*.jpg')
zpics.sort()
for xx in range(0,len(zpics)):
shutil.copy(zpics[xx], h_user + '/Pictures/')
# move MP4s to USB if present
USB_Files = []
USB_Files = (os.listdir(m_user))
if len(USB_Files) > 0:
usedusb = os.statvfs(m_user + "/" + USB_Files[0] + "/")
USB_storage = ((1 - (usedusb.f_bavail / usedusb.f_blocks)) * 100)
if len(USB_Files) > 0 and USB_storage < 90:
spics = glob.glob(h_user + '/Videos/*.mp4')
spics.sort()
for xx in range(0,len(spics)):
movi = spics[xx].split("/")
if not os.path.exists(m_user + "/'" + USB_Files[0] + "'/" + movi[4]):
shutil.move(spics[xx],m_user[0] + "/'" + USB_Files[0] + "'/")
if use_gpio == 1 and fan_ctrl == 1:
led_fan.value = 0
pygame.quit()
poll = p.poll()
if poll == None:
os.killpg(p.pid, signal.SIGTERM)
time.sleep(5)
os.system("sudo shutdown -h now")
# set fan speed
if fan_ctrl == 1:
fan_timer = time.monotonic()
cpu_temp = str(CPUTemperature()).split("=")
temp = float(str(cpu_temp[1])[:-1])
dc = ((temp - fan_low)/(fan_high - fan_low))
dc = max(dc,.25)
dc = min(dc,1)
if temp > fan_low and use_gpio == 1:
led_fan.value = dc
if menu ==4 :
text(0,7,1,0,1,"Fan High " + str(int(dc*100)) + "%",14,7)
elif temp < fan_low and use_gpio == 1:
led_fan.value = 0
if menu == 4:
text(0,7,2,0,1,"Fan High degC",14,7)
# get RAM free space
st = os.statvfs("/run/shm/")
freeram = (st.f_bavail * st.f_frsize)/1100000
# check subprocess running
poll = p.poll()
if poll != None and trace == 1: