简体   繁体   English

cv2 VideoCapture 在启动时挂起 flask 服务器

[英]cv2 VideoCapture hangs flask server on startup

Flask server hangs at startup (and doesn't serve any page). Flask 服务器在启动时挂起(并且不提供任何页面)。 This happens because is trying to initialize OpenCV VideoCapture inside a class:发生这种情况是因为试图在 class 中初始化 OpenCV VideoCapture:

I have a LaptopCamera class that initializes the laptop camera using OpenCV:我有一个LaptopCamera初始化笔记本电脑摄像头的 LaptopCamera class:

class LaptopCamera:
    def __init__(self):
        self.video = cv2.VideoCapture(0)
        self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
        self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
        self.video.set(cv2.CAP_PROP_FPS, 60)
        self.video.set(cv2.CAP_PROP_BUFFERSIZE, 1)

    def single_image(self):
        """return jpeg image of frame"""
        ret, jpeg = cv2.imencode('.jpeg', self.read_video())
        return jpeg.tobytes()

and then it is used in the flask server like this:然后在 flask 服务器中使用,如下所示:

@API.route('/picture.jpeg')
def provide_jpeg():
    cam.read_video()
    return Response(cam.single_image(), mimetype='image/jpeg')

cam = LaptopCamera()

if __name__ == '__main__':
    tankyAPI.run(HOST, PORT, debug=True)

If I first comment cam = LaptopCamera() , start the server, uncomment the cam = LaptopCamera() and wait for it to reload it works just fine.如果我首先评论cam = LaptopCamera() ,启动服务器,取消注释cam = LaptopCamera()并等待它重新加载它就可以了。

I am wondering why does this happen?我想知道为什么会这样? and how could I find a solution?我怎么能找到解决方案?

I have a similar experience when developing my application.在开发我的应用程序时,我也有类似的经历。 The solution I had was to remove all the libraries, and create a new environment, and re-install all the libraries.我的解决方案是删除所有库,创建一个新环境,然后重新安装所有库。 It was on Ubuntu 18, and there are some system libraries that are different between the CV2 and other python modules, so the easiest way to solve my problem is to start from scratch and to reinstall every library.它在 Ubuntu 18 上,CV2 和其他 python 模块之间存在一些不同的系统库,所以解决我的问题的最简单方法是从头开始并重新安装每个库。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM