How can I get time of a frame with opencv or others?

Question:

I need to process the video and register some events, in order to do this I iterate over all frames and get that information, but I need to know the second in the video where that frame appears.

Currently, I am using Opencv like this:

    cap = cv2.VideoCapture(path_str)

    while cap.isOpened():
        _, frame = cap.read()

        if frame is None:
            break

        data = self.get_data()
        store(data, second_of_the_video)

        if cv2.waitKey(25) & 0xFF == ord("q"):
            break

    cap.release()

The problem is that I am not sure how to get the second_of_the_video I can get the frame, but I am not sure how to "sync" the frame over video duration.

Any idea about how can I do that?

Thanks.

Asked By: Tlaloc-ES

||

Answers:

You can use the get(propId) method of the VideoCapture class to get the current position of the video in milliseconds. Then you can calculate the current second by dividing the position by 1000.

Here’s an example of how you can get the current second of the video in your code:

cap = cv2.VideoCapture(path_str)

while cap.isOpened():
    _, frame = cap.read()

    if frame is None:
        break

    data = self.get_data()
    position = cap.get(cv2.CAP_PROP_POS_MSEC)
    second_of_the_video = position / 1000
    store(data, second_of_the_video)

    if cv2.waitKey(25) & 0xFF == ord("q"):
        break

cap.release()

Note that the frame rate of the video may not be constant, so the time between frames may not be exactly 25 milliseconds. So you should use CAP_PROP_POS_MSEC to get the current position rather than just incrementing a variable by 25.

Answered By: Migl Araújo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.