I created a web application by using Flask, in order to trigger a detection routine through HTTP request.
Basically, every time a GET request is sent to the endpoint URL, I want a function to be executed.
The code I'm using is:
web_app = Flask(__name__)
@web_app.route('/test/v1.0/run', methods=['GET'])
def main():
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
while(True):
ret, frame = cap.read()
***performing operations on each frame and running ML models on them***
return ('', 204)
if __name__ == '__main__':
web_app.run(debug=True)
Everything works fine the first time, if I use:
curl -i http://localhost:5000/test/v1.0/run
the function main() is executed, and at the end the results are uploaded to an online database.
After this, the program keeps listening on the URL. If I send another GET request, main() is executed again, but it hangs after the first iteration of the while loop.
I tried simply running the same code multiple times by placing it in a for loop:
for i in range(10):
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
while(True):
ret, frame = cap.read()
***performing operations on each frame and running ML models on them***
and it works without any problem, so the hanging should not depend on anything I'm doing inside the code.
The problem should be caused by the fact that I'm using flask to trigger the function, but in this case I don't understand why main() hangs after starting. I'm very new to flask and web applications in general, so I'm probably missing something very simple here.
The problem was that I was also displaying the frames collected from camera, using
cv2.imshow("window", frame)
and, even if at the end of the program I was closing everything by:
cap.release()
cv2.destroyAllWindows()
something remained hanging, and it got the process stuck at the next iteration. I solved by removing the cv2.imshow...I don't really need to visualize the stream, so I can live with it. Mostly out of curiosity though, I'll try to figure out how to make it work even when visualizing the video frames.