python -- opencv获取摄像头时,运行一段时间后突然停止

问题:
        在pycharm社区版中,使用opencv获取摄像头时,运行一段时间后,rtsp流突然断开(有概率)。

断开时报错:

websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason



怎么解决?
求大佬们告知!!!代码如下
```python  ---- server.py

import base64
import cv2
from flask import Flask
from flask_sockets import Sockets
from imutils.video import FileVideoStream
import asyncio
import websockets

app = Flask(__name__)
sockets = Sockets(app)
fvs = FileVideoStream(1).start()
async def video_stream(websocket, path):
    cap = cv2.VideoCapture(1)
    cap.set(6, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
    while True:
        ret, img = cap.read()
        if not ret:
            # 若没有帧返回,则重新刷新rtsp视频流
            cap = cv2.VideoCapture(1)
            ret, frame = cap.read()
            continue
        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 50]
        result, img_encode = cv2.imencode('.jpg', img, encode_param)
        image_b = base64.b64encode(img_encode).decode()
        await websocket.send(image_b)
        print(type(image_b))


if __name__ == "__main__":
   start_server = websockets.serve(video_stream, 'localhost', 8778)
   asyncio.get_event_loop().run_until_complete(start_server)
   asyncio.get_event_loop().run_forever()

```
```python   ------   client.py

import base64
import datetime
import cv2
import numpy as np
import asyncio
import websockets

now = datetime.datetime.now()
print(now)


async def send_query_webSocket():
    url = "ws://localhost:8778"
    async with websockets.connect(url, ping_interval=None) as websocket:
        while True:
            greeting = await websocket.recv()
            image0 = base64.b64decode(greeting)
            image1 = np.frombuffer(image0, np.uint8)
            images = cv2.imdecode(image1, cv2.IMREAD_COLOR)

            cv2.imshow("re", images)
            cv2.waitKey(1)
            # cv2.destroyAllWindows()
            print(type(greeting))


if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(send_query_webSocket())


```

你可能感兴趣的:(问题,python,opencv,flask)