本文介绍了Python opencv cv2.VideoCapture.read() 第一次运行后无限期卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 上使用 opencv,但遇到了 cv2.VideoCapture.read() 函数卡住的问题.这是一些原型代码:

I am using opencv on python and I'm facing an issue where the cv2.VideoCapture.read() function gets stuck. Here's some prototype code:

要求.txt

opencv-contrib-python==4.1.1.26

应用程序.py

import cv2

def run_analysis(path_to_video):
    vs = cv2.VideoCapture(path_to_video)

    while True:
         frame = vs.read()
         if frame is None:
             break
         do_stuff_with_frame(frame)

    vs.release()

这段代码在我的 Mac 上一直有效.它仅在我第一次将其作为 Flask 应用程序部署到 Elastic Beanstalk(在 Red Hat Linux 上运行)时才有效.我在 github 问题中看到一些可能表明 vs.release() 无法释放文件指针或内存泄漏的内容,但我对这些概念不太了解.

This code works all the time on my mac. It works only the first time around when I deploy it as a Flask app to Elastic Beanstalk (runs on Red Hat Linux).I've seen some stuff in github issues that might suggest that vs.release() fails to release the file pointer, or that there's a memory leak, but I'm not too well versed in these concepts.

即使我无法得到原因的答案,我也会很高兴以一种蛮力的方式让它发挥作用.

Even if I can't get an answer for why, I'd be happy with a brute force way of making it work.

推荐答案

您可以添加保护以确保 cv2.VideoCapture() 处理程序对象对 isOpened() 有效代码>.此外,您可以检查 read()status 返回值,以确保帧有效.还要确保提供给处理程序的路径有效.

You can add guards to ensure that the cv2.VideoCapture() handler object is valid with isOpened(). In addition, you can check the status return value from read() to ensure that the frame is valid. Also ensure that the path given to the handler is valid.

import cv2

def run_analysis(path_to_video):
    cap = cv2.VideoCapture(path_to_video)

    if not cap.isOpened():
        print("Error opening video")

    while(cap.isOpened()):
        status, frame = cap.read()
        if status:
            cv2.imshow('frame', frame)
            # do_stuff_with_frame(frame)
        key = cv2.waitKey(25)
        if key == ord('q'):
            break

if __name__ == "__main__":
    run_analysis('video.mp4')

这篇关于Python opencv cv2.VideoCapture.read() 第一次运行后无限期卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 04:45