mercredi 23 janvier 2019

Problem with multiple instances of VideoCapture in python cv2

For my project I wanted to create a subclass to opencv VideoCapture, which looks like that:

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

Then I wrote some tests using unittest. Since I want a fresh instance of my subclass, I decided to create it in setUp() function. Tests (incomplete) look as follows:

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()

But even though there are 4 tests, only 1 is executed and it always end with information about some exit code like that:

enter image description here

When I just define vid_op as class field and not try to initialize it at the beginning of each test, everything works perfectly. Is it impossible to create multiple instances of VideoCapture class even though I release each before creating another? Or is the problem somewhere else?

Aucun commentaire:

Enregistrer un commentaire