I want to use the list frame_buffer in both functions update_frame and get_stream these 2 fucntions are called in different threads but I am using a lock object so I am stumped by this please help.
import cv2
import time
from flask import Flask, Response
from flask_socketio import SocketIO, emit
import threading
import detect
import queue
app = Flask(__name__)
socketio = SocketIO(app)
frame_lock = threading.Lock()
global frame_buffer
frame_buffer = queue.Queue(maxsize=10)
def update_frame(image):
""" Update the frame buffer with encoded image data. """
global frame_buffer
ret, buffer = cv2.imencode('.jpg', image)
if ret:
frame_lock.acquire()
if frame_buffer.full():
frame_buffer.get_nowait() # Remove oldest frame
frame_buffer.put(buffer.tobytes())
print("Frame added to buffer. Current buffer size:", frame_buffer.qsize())
frame_lock.release()
else:
print("WARNING: Frame encoding failed.")
time.sleep(0.1) # Limit the rate of frames being added
def get_stream():
""" Generator function to stream video from the buffer. """
global frame_buffer
print("getstream:",frame_buffer.qsize())
frame_lock.acquire()
frame_data = frame_buffer.get()
if frame_data != None:
yield (b'--framern'
b'Content-Type: image/jpegrnrn' + frame_data + b'rn')
else:
print("Buffer empty. Waiting for frames...")
frame_lock.release()
@app.route('/')
def index():
return '''<html>
<head>
<title>Live Stream</title>
<script>
function refreshImage() {
var img = document.getElementById('stream');
img.src = '/video_feed?' + new Date().getTime();
}
setInterval(refreshImage, 100); // Refresh every 100 milliseconds
</script>
</head>
<body>
<h1>Live Stream</h1>
<img id="stream" src="/video_feed" width="640" height="480">
</body>
</html>'''
@app.route('/video_feed')
def video_feed():
return Response(get_stream(), mimetype='multipart/x-mixed-replace; boundary=frame')
@socketio.on('connect')
def handle_connect():
print('Client connected')
emit('stream_start', broadcast=True) # Let clients know that the stream has started
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')
def run_web():
print("Starting Flask server...")
app.run(host='0.0.0.0', debug=False, threaded=True)
if __name__ == '__main__':
cam_thread = threading.Thread(target=detect.runDetect)
cam_thread.start() # Start the camera thread to update frames
app.run(host='0.0.0.0', debug=False, threaded=True)
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print("Shutting down...")
I tried many things that were suggested by chatgpt and I couldn’t reach a solution. I am trying to stream the yolov5 detection window so what I did was create a function called update_frame that takes as argument an image and call it inside the detect.py of yolov5 in the same script of update_frame I am using flask to create a webpage that has an that gets updated using that frame I retrieved but for some reason the global variable is not the same in both functions
Nizar Shehayeb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.