Python cv2中多个VideoCapture实例的问题

3

为了我的项目,我想创建一个opencv VideoCapture的子类,如下所示:

import cv2

class VideoOperator(cv2.VideoCapture):
    def __init__(self, video_path):
        super().__init__(video_path)
        self.current_frame_index = 0
        self.last_frame_index = int(self.get(cv2.CAP_PROP_FRAME_COUNT) - 1)

    def move_to_frame(self, frame_index):
        if frame_index > self.last_frame_index:
            self.set(cv2.CAP_PROP_POS_FRAMES, self.last_frame_index)
            self.current_frame_index = self.last_frame_index
        elif frame_index < 0:
            self.set(cv2.CAP_PROP_POS_FRAMES, 0)
            self.current_frame_index = 0
        else:
            self.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
            self.current_frame_index = frame_index

    def move_x_frames(self, x):
        self.move_to_frame(self.current_frame_index + x)

    def get_current_frame(self):
        _, image = self.read()
        self.move_to_frame(self.current_frame_index)
        return image

然后我使用unittest编写了一些测试。由于我想要一个新的子类实例,所以我决定在setUp()函数中创建它。不完整的测试如下:

import unittest, time
import video_operator

class TestVideoOperator(unittest.TestCase):
    def setUp(self):
        self.vid_op = video_operator.VideoOperator(r'E:\PythonProjects\video_cutter\vid1.mp4')

    def tearDown(self):
        self.vid_op.release()


    def test_init(self):
        self.assertEqual(self.vid_op.current_frame_index, 0)
        self.assertEqual(self.vid_op.last_frame_index, 430653)

    def test_move_to_existing_frame(self):
        self.vid_op.move_to_frame(100)
        self.assertEqual(self.vid_op.current_frame_index, 100)

    def test_move_to_negative_frame(self):
        self.vid_op.move_to_frame(-100)
        self.assertEqual(self.vid_op.current_frame_index, 0)

    def test_move_to_non_existing_frame(self):
        self.vid_op.move_to_frame(self.vid_op.last_frame_index + 100)
        self.assertEqual(self.vid_op.current_frame_index, self.vid_op.last_frame_index)

if __name__ == '__main__':
    unittest.main()

但是,尽管有4个测试,只有1个被执行,并且它总是以一些退出代码的信息结束,例如:enter image description here。当我只将vid_op定义为类字段而不尝试在每个测试开始时初始化它时,一切都运行得很完美。即使在释放每个VideoCapture实例之前,创建多个实例也是不可能的吗?还是问题出在其他地方?
1个回答

0
你是否给予足够的时间让VideoCapture初始化? 我正在使用cv2并行读取16个RTSP摄像头。它需要几乎/超过1分钟来初始化。 在我的情况下,我不能使用VideoCapture.read()因为处理工作太多了。我通过运行cap.grab()在高速循环中丢弃一些帧并仅抓取一些帧,我想要显示的帧我使用cap.retrieve()这样我只解码我感兴趣的帧并提高应用程序性能。例如,为了以3FPS的基础显示30FPS相机中的相机,您应该每10帧间隔取1帧。 另一个要提到的是,Linux已经证明比Windows 10更好地处理这些VideoCapture对象。 即使是树莓派也可以在几分钟的初始化后并行运行多个VideoCaptures。 希望这些信息有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接