-
Notifications
You must be signed in to change notification settings - Fork 1
/
camera_flask_app.py
161 lines (132 loc) · 4.59 KB
/
camera_flask_app.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
import datetime
import os
import time
from threading import Thread
import cv2
import numpy as np
from flask import Flask, render_template, Response, request
global capture, rec_frame, grey, switch, neg, face, rec, out
capture = 0
grey = 0
neg = 0
face = 0
switch = 1
rec = 0
# make shots directory to save pics
try:
os.mkdir('./shots')
except OSError as error:
pass
# Load pretrained face detection model
net = cv2.dnn.readNetFromCaffe('./saved_model/deploy.prototxt.txt',
'./saved_model/res10_300x300_ssd_iter_140000.caffemodel')
# instatiate flask app
app = Flask(__name__, template_folder='./templates')
camera = cv2.VideoCapture(0)
def record(out):
global rec_frame
while rec:
time.sleep(0.05)
out.write(rec_frame)
def detect_face(frame):
global net
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,
(300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
detections = net.forward()
confidence = detections[0, 0, 0, 2]
if confidence < 0.5:
return frame
box = detections[0, 0, 0, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
try:
frame = frame[startY:endY, startX:endX]
(h, w) = frame.shape[:2]
r = 480 / float(h)
dim = (int(w * r), 480)
frame = cv2.resize(frame, dim)
except Exception as e:
pass
return frame
def gen_frames(): # generate frame by frame from camera
global out, capture, rec_frame
while True:
success, frame = camera.read()
if success:
if face:
frame = detect_face(frame)
if grey:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if neg:
frame = cv2.bitwise_not(frame)
if capture:
capture = 0
now = datetime.datetime.now()
p = os.path.sep.join(['shots', "shot_{}.png".format(str(now).replace(":", ''))])
cv2.imwrite(p, frame)
if rec:
rec_frame = frame
frame = cv2.putText(cv2.flip(frame, 1), "Recording...", (0, 25), cv2.FONT_HERSHEY_SIMPLEX, 1,
(0, 0, 255), 4)
frame = cv2.flip(frame, 1)
try:
ret, buffer = cv2.imencode('.jpg', cv2.flip(frame, 1))
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
except Exception as e:
pass
else:
pass
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/requests', methods=['POST', 'GET'])
def tasks():
global switch, camera
if request.method == 'POST':
if request.form.get('click') == 'Capture':
global capture
capture = 1
elif request.form.get('grey') == 'Grey':
global grey
grey = not grey
elif request.form.get('neg') == 'Negative':
global neg
neg = not neg
elif request.form.get('face') == 'Face Only':
global face
face = not face
if face:
time.sleep(4)
elif request.form.get('stop') == 'Stop/Start':
if switch == 1:
switch = 0
camera.release()
cv2.destroyAllWindows()
else:
camera = cv2.VideoCapture(0)
switch = 1
elif request.form.get('rec') == 'Start/Stop Recording':
global rec, out
rec = not rec
if rec:
now = datetime.datetime.now()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('vid_{}.avi'.format(str(now).replace(":", '')), fourcc, 20.0, (640, 480))
# Start new thread for recording the video
thread = Thread(target=record, args=[out, ])
thread.start()
elif not rec:
out.release()
elif request.method == 'GET':
return render_template('index.html')
return render_template('index.html')
if __name__ == '__main__':
app.run()
camera.release()
cv2.destroyAllWindows()