Python 在N次之后终止cv2读取进程
我绝望了 我的代码在视频中读取nframe,有时代码只是无缘无故地停止,并且没有错误。 所以我决定以某种方式提出一个错误。 问题是,代码确实会引发错误,但出于某种原因它会忽略它,并正常工作 *我提供了一个代码块,在这个代码块上使用完全相同的方法 处理程序:Python 在N次之后终止cv2读取进程,python,python-3.x,Python,Python 3.x,我绝望了 我的代码在视频中读取nframe,有时代码只是无缘无故地停止,并且没有错误。 所以我决定以某种方式提出一个错误。 问题是,代码确实会引发错误,但出于某种原因它会忽略它,并正常工作 *我提供了一个代码块,在这个代码块上使用完全相同的方法 处理程序: def handler(signum,frame): print("error") ## This is printed raise Exception('time out') ## I guess this is
def handler(signum,frame):
print("error") ## This is printed
raise Exception('time out') ## I guess this is getting raised
我要包装的代码部分:
for i in range(0,int(frame_count), nframe): # basicly loads every nframe from the video
try:
frame = video.set(1,i)
signal.signal(signal.SIGALRM), handler)
signal.alarm(1) # At this point, the 'handler' did raise the error, but it did not kill this 'try' block.
_n,frame = video.read() # This line sometimes gets for infinit amount of time, and i want to wrap it
except Exception as e:
print('test') # Code does not get here, yet the 'handler' does raise an exception
raise e
# Here i need to return False, or rise an error, but the code just does not get here.
使用完全相同的方法的示例:
import signal
import time
def handler(signum, frame):
raise Exception('time out')
def function():
try:
signal.signal(signal.SIGALRM,handler)
signal.alarm(5) # 5 seconds till raise
time.sleep(10) # does not get here, an Exception is raised after 5 seconds
except Exception as e:
raise e # This will indeed work
我猜
read()
调用在C代码中的某个地方被阻塞了。信号处理程序运行时,会将异常放入Python解释器的某个位置,但在Python解释器重新获得控制之前,不会处理异常。这是一个限制:
纯用C语言实现的长时间运行的计算(例如在大量文本上进行正则表达式匹配)可能会在任意时间内不间断地运行,而与接收到的任何信号无关。计算完成后将调用Python信号处理程序
一种可能的解决方法是使用多处理
模块读取单独进程上的帧,然后使用多处理.Queue
将帧返回到主进程(从中可以通过超时获取
)。但是,在进程之间发送帧会有额外的开销
另一种方法可能是试图避免问题的根源。OpenCV有不同的视频后端(V4L、GStreamer、ffmpeg等);其中一个可能在另一个不工作的地方工作。使用VideoCapture
构造函数的第二个参数,可以指示要使用哪个后端的首选项:
cv.VideoCapture(..., cv.CAP_FFMPEG)
有关后端的完整列表,请参见。取决于您的平台和OpenCV版本,并非所有版本都可用。您忽略了
video.read()
(此处称为\n
)的第一个返回值。你确定这不仅仅是返回False
,而且是你自己的代码永远在循环吗?当该值为False
时,您通常希望退出循环:是的,问题不是反复循环,代码确实在运行。我将尝试这种方法,问题是,我猜u有时只是不返回,代码被卡住了。我用一个指示器试了一下,并打印了每个迭代,但它只是冻结在一个迭代中。。在那之后没有任何迹象表明,它只是花了无限的时间来阅读图片或其他东西…太好了,谢谢!我将尝试这些方法。