[英]Stop the thread running when leaving page
即時通訊使用這個家伙代碼,所以我可以從我的PiCamera視頻流
camera_pi.py:
import time
import io
import threading
import picamera
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
def __init__(self):
if self.thread is None:
# start background frame thread
self.thread = threading.Thread(target=self._thread)
self.thread.start()
# wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
return self.frame
@classmethod
def _thread(cls):
with picamera.PiCamera() as camera:
# camera setup
camera.resolution = (1280, 720)
camera.hflip = False
camera.vflip = False
# let camera warm up
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
# store frame
stream.seek(0)
cls.frame = stream.read()
# reset stream for next frame
stream.seek(0)
stream.truncate()
Main Flask App(這是我的代碼的一部分:
from camera_pi import Camera
@app.route('/video_feed')
def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
def gen(camera):
"""Video streaming generator function."""
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
Stream.html:
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Live Streaming</h1>
</div>
<div class="panel-body">
<img id="pic" src="{{ url_for('video_feed') }}" alt="live stream link" class="img-responsive img-rounded"></img>
</div>
</div>
在我渲染stream.html頁面並調用流功能之前,我的整個項目工作正常。 當您實際加載另一個頁面時,似乎流線程仍在運行嗎? 我離開stream.html頁面時,有什么方法可以殺死線程嗎? 離開stream.html意味着您不再流媒體,因此不需要運行線程。 原因是無緣無故地殺死了我的pi記憶。
不支持終止線程。 只需在線程循環中添加全局標志檢查即可,例如:
for foo in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
if stop_the_thread: break
(在循環之后,請執行任何操作以正確關閉相機,如果有的話)。
在您的主代碼中,首先將global stop_the_thread
設置為False
,然后在確定線程必須停止時將其設置為True
。
在這種特定情況下,使用類屬性cls.stop_the_thread
而不是實際的全局變量更為優雅,但這不會影響關鍵概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.