为了我的项目,我想创建一个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个被执行,并且它总是以一些退出代码的信息结束,例如:。当我只将vid_op定义为类字段而不尝试在每个测试开始时初始化它时,一切都运行得很完美。即使在释放每个VideoCapture实例之前,创建多个实例也是不可能的吗?还是问题出在其他地方?