-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecurityCamera.py
212 lines (177 loc) · 6.39 KB
/
SecurityCamera.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
# IMPORTS
import glob
import os
import datetime
import json
import cv2 as cv
import time
# FUNCTIONS
# Load the config into global variables and then start the work
def loadConfig(file):
global conf, imgPath, vidPath
conf = json.load(open(f"./cfg/{file}.json"))
imgPath = f"./{conf['dirImg']}"
vidPath = f"./{conf['dirVid']}"
if not os.path.exists(imgPath):
os.mkdir(imgPath)
if not os.path.exists(vidPath):
os.mkdir(vidPath)
work()
# Returns true if cfgFile is found cfg folder
def checkCFG(cfgFile):
return os.path.exists("./cfg/"+cfgFile+".json")
# A wrapper around datetimeOBJ with .strftime('%Y-%m-%d_%H_%M_%S_%f')
def getTimeNow():
return datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S_%f')
# Adds message to frame
def addTS(frame, message): # draw the text and timestamp on the frame
cv.putText(frame, message, (10,
frame.shape[0] - 10), cv.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
# Returns contours: Did it to clean-up the code in work()
def getCnts(diff):
gray = cv.cvtColor(diff, cv.COLOR_RGB2GRAY)
blur = cv.GaussianBlur(gray, (5, 5), 0)
thresh = cv.threshold(blur, 20, 255, cv.THRESH_BINARY)[1]
dilated = cv.dilate(thresh, None, iterations=3)
cnts, _ = cv.findContours(dilated, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
return cnts
# Returns true if there is any motion
def isMotion(cnts):
for c in cnts:
if cv.contourArea(c) > 36000:
return True
return False
def work():
global cam
cam = cv.VideoCapture(0)
NMFR = conf["NMFR"]
time.sleep(5)
# Saving original after 5 seconds to get a better photo for reference
original = cam.read()[1]
cv.imwrite("./Images/original.jpeg", original)
# Motion controls
motionFlag = False
motionCounter = 0
while cam.isOpened():
# Indicates motion frames for testing purpose
print(motionCounter)
frame = cam.read()[1]
cnts = getCnts(cv.absdiff(original, frame))
title = getTimeNow()
if isMotion(cnts):
NMFR = conf["NMFR"]
record(frame, title)
motionCounter+=1
motionFlag=True
else:
if NMFR <=0:
motionFlag = False
if NMFR > 0 and motionFlag == True:
NMFR -= 1
record(frame, title)
if conf["showVideo"]:
cv.imshow("Security Feed", frame)
key = cv.waitKey(1) & 0xFF
if key == ord("q"):
img2Video()
break
if cv.waitKey(10) == ord('q'):
img2Video()
break
# A function to record frames one by one
def record(frame, title):
folder = f"{imgPath}{title[0:13]}"
if not os.path.exists(folder):
os.mkdir(folder)
addTS(frame, title)
cv.imwrite(f"{imgPath}{title[0:13]}/{title}.jpeg", frame)
# To convert all the frames to 1 video file: part 2
def recordVideoFromFolder(folder):
size = (640, 480)
img_array = []
for filename in glob.glob(f'{imgPath}{folder}/*.jpeg'):
img = cv.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
out = cv.VideoWriter(f'{vidPath}{folder}.avi', cv.VideoWriter_fourcc(*'DIVX'), 30, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
# To convert all the frames to 1 video file: part 1
def img2Video():
dirList = [f for f in os.listdir(imgPath) if os.path.isdir(imgPath+f)]
for folder in dirList:
recordVideoFromFolder(folder)
# MAIN
instructions = '''
### START
--> To start camera and recording with default settings choose option 1
### MAKE A CONFIG FILE
--> To make a new config file copy the contents from default("default.json") config and paste it into a new file and save that file to cfg folder with a name.
### DELETE A CONFIG FILE
--> Just delete the file from cfg folder after closing the application
### DEFAULT CONFIG
--> It is the default config file of the security camera
### GENERAL
-> All the config files will be stored in the "cfg" folder.
-> Unless any config file is deleted manually, it will stay there.
-> To make a custom config as default, delete the default("default.json") config and rename new config as "default.json".
'''
os.system("cls")
toolName = '''
_____ _ _ _____ _____ _____ _____ _____ _____
| __|___ ___ _ _ ___|_| |_ _ _ | | _ | | __| __ | _ |
|__ | -_| _| | | _| | _| | | | --| | | | | __| -| |
|_____|___|___|___|_| |_|_| |_ | |_____|__|__|_|_|_|_____|__|__|__|__|
|___|
by github.com/prakharsaxena1
'''
print(f'''{toolName}\n1. Enter config file name\n2. Start with default config\n3. Help\n4. Exit\n''')
# Globals
conf = None
imgPath = None
vidPath = None
cam = None
# Input option to use Security Camera
option = input("Choose option (number): ")
# Navigation Logic
if option == "1":
configName = input("Config name(Full path): ")
if checkCFG(configName):
print("Config loaded successfully")
loadConfig("default")
else:
print("No config found at ./cfg/")
exit()
elif option == "2":
print("Starting with default config")
if checkCFG("default"):
loadConfig("default")
else:
print("No config found at ./cfg/")
exit()
elif option == "3":
if cam != None:
cam.release()
os.system("cls")
print(f'''
_____ _____ __ _____
| | | __| | | _ |
| | __| |__| __|
|__|__|_____|_____|__|
{instructions}''')
elif option == "4":
print('''
_ _ _ _____ _ _ _____ _____ _____ _____ _____ _____
___ _ _|_| |_|_|___ ___ | __|___ ___ _ _ ___|_| |_ _ _ | | _ | | __| __ | _ |
| -_|_'_| | _| | | . | |__ | -_| _| | | _| | _| | | | --| | | | | __| -| |_ _ _
|___|_,_|_|_| |_|_|_|_ | |_____|___|___|___|_| |_|_| |_ | |_____|__|__|_|_|_|_____|__|__|__|__|_|_|_|
|___| |___|
by github.com/prakharsaxena1
''')
if cam != None:
cam.release()
exit()
else:
print("Wrong option")