我有帶有 Flask 框架的 python 應用程序。我在我的索引頁面上顯示來自攝像頭的視頻流,如下所示: <img id="bg2" src="{{ url_for('video') }}" width="400px" height="400px">一切正常,但如果我直接刷新頁面,奇怪的事情就會開始發生。如果我轉到另一個頁面并返回索引,一切也都有效。這些是我得到的錯誤(每次都是其中之一):對象 0x7fc579e00240 錯誤:未分配正在釋放的指針斷言 fctx->async_lock 在 libavcodec/pthread_frame.c:155 失敗要么分段錯誤 11這是數據來自的端點:@app.route('/video')def video(): return Response(video_stream(), mimetype='multipart/x-mixed-replace; boundary=frame')def video_stream(): global video_camera # Line 1 ---------------------- if video_camera == None: # Line 2 ---------------------- video_camera = VideoCamera() while True: frame = video_camera.get_frame() if frame != None: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')如果我刪除注釋行,一切正常,但由于新對象的不斷初始化,它又慢又重。這是我的相機對象,如果有幫助的話class VideoCamera(object): def __init__(self): self.cap = cv2.VideoCapture(0) def __del__(self): self.cap.release() def get_frame(self): ret, frame = self.cap.read() print(ret) if ret: ret, jpeg = cv2.imencode('.jpg', frame) return jpeg.tobytes()
1 回答

慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
好的,所以一種解決方案是不使用全局對象。這是新的 video_stream() 函數:
def video_stream():
video_camera = VideoCamera();
...
另一種可能的解決方案是像這樣使用線程鎖:
def video_stream():
global video_camera
if video_camera == None:
video_camera = VideoCamera()
while True:
with lock:
frame = video_camera.get_frame()
if frame != None:
global_frame = frame
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
添加回答
舉報
0/150
提交
取消