Hello, I have been working on a project which has not let me sleep for a while now
import subprocess
import sys
from imutils.video import VideoStream
import imutils
import numpy as np
import cv2
import pickle
import time
from flask import *
import os, sys
app = Flask(__name__)
# Load face detector, face embedding model, recognizer, and label encoder
protoPath = "face_detector/deploy.prototxt"
modelPath = "face_detector/res10_300x300_ssd_iter_140000.caffemodel"
detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)
embedder = cv2.dnn.readNetFromTorch("face_detector/openface_nn4.small2.v1.t7")
recognizer = pickle.loads(open("output/recognizer.pickle", "rb").read())
le = pickle.loads(open("output/le.pickle", "rb").read())
# Global variable to store the current class label
current_label = ""
entered_username = ""
username_printed = False
def generate_frames(entered_username):
global current_label, username_printed
vs = VideoStream(src=0).start()
time.sleep(2.0)
last_print_time = time.time()
while True:
frame = vs.read()
frame = imutils.resize(frame, width=600)
(h, w) = frame.shape[:2]
imageBlob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300),
(104.0, 177.0, 123.0), swapRB=False, crop=False)
detector.setInput(imageBlob)
detections = detector.forward()
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
face = frame[startY:endY, startX:endX]
(fH, fW) = face.shape[:2]
if fW < 20 or fH < 20:
continue
faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255, (96, 96), (0, 0, 0), swapRB=True, crop=False)
embedder.setInput(faceBlob)
vec = embedder.forward()
preds = recognizer.predict_proba(vec)[0]
j = np.argmax(preds)
proba = preds[j]
name = le.classes_[j]
current_label = name # Update the global variable with the current class label
text = "{}: {:.2f}%".format(name, proba * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
# Check if the username has been entered and not printed yet
if entered_username and not username_printed:
print("Username entered:", entered_username)
username_printed = True
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# Check if 10 seconds have passed since the last print
if time.time() - last_print_time >= 5:
print("Current label:", current_label)
last_print_time = time.time()
print("entered username : ", entered_username)
if current_label == entered_username:
vs.stop()
print('redirecting....')
index() # Call index function directly
@app.route('/')
def index():
return render_template('login.html', current_label=current_label)
@app.route('/video_feed')
def video_feed():
global entered_username
return Response(generate_frames(entered_username), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/setUsername', methods=['POST'])
def set_username():
global entered_username
entered_username = request.json.get('username')
return redirect('/home')
@app.route('/home')
def home():
return render_template('index.html')
if __name__=='__main__':
app.run(debug=True)
this is the source code, here's the flow of the program,
a. I will execute the code that starts the server
b. I will enter the username on the webpage and click submit
c. face recognition module will identify the face from live camera feed and return class label
d. if the entered username and class label are same, then I want to redirect to index.html
the first three steps are working well and fine, last step I am getting the following error,
127.0.0.1 - - [29/Apr/2024 11:55:44] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Apr/2024 11:55:44] "GET /static/style_face.css HTTP/1.1" 304 -
127.0.0.1 - - [29/Apr/2024 11:55:44] "GET /static/img_2.webp HTTP/1.1" 304 -
127.0.0.1 - - [29/Apr/2024 11:55:47] "POST /setUsername HTTP/1.1" 302 -
127.0.0.1 - - [29/Apr/2024 11:55:47] "GET /home HTTP/1.1" 200 -
Username entered: kumar
127.0.0.1 - - [29/Apr/2024 11:55:49] "GET /video_feed HTTP/1.1" 200 -
Current label: kumar
entered username : kumar
redirecting....
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/werkzeug/wsgi.py", line 256, in __next__
return self._next()
File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/werkzeug/wrappers/response.py", line 32, in _iter_encoded
for item in iterable:
File "/home/kumar/Downloads/Multi disease prediction(update 21-03-2024)/new_app_2.py", line 95, in generate_frames
index() # Call index function directly
File "/home/kumar/Downloads/Multi disease prediction(update 21-03-2024)/new_app_2.py", line 99, in index
return render_template('login.html', current_label=current_label)
File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/flask/templating.py", line 148, in render_template
app = current_app._get_current_object() # type: ignore[attr-defined]
File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/werkzeug/local.py", line 508, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
Can someone please help me out here?
Top comments (0)