angie
angie

Reputation: 3

How can I read m3u8 format video stream and save it with opencv in python?

I'm trying to save video stream, and to timelapse it. I know how to read any video from computer (for example mp4 format) and make a timelapse (I tried, I succeeded). Now I'm trying to do the same with a video stream. I have link for m3u8 video https://wstream.comanet.cz:1943/live/Vrchlabi-sjezdovka2.stream_360p/playlist.m3u8, I'm reading video like this: (Initialization:)

import cv2 as cv
url = 'https://wstream.comanet.cz:1943/live/Vrchlabi-sjezdovka2.stream_360p/playlist.m3u8'
fourcc = cv.VideoWriter_fourcc(*'mp4v')
height = video.get(cv.CAP_PROP_FRAME_HEIGHT)
width = video.get(cv.CAP_PROP_FRAME_WIDTH)
outp = cv.VideoWriter(save_path, fourcc, 60,(int(width), int(height)))
video = cv.VideoCapture("url")

dir_stream = "streamframes"

if not os.path.exists(dir_stream):
    os.makedirs(dir_stream)

if not video.isOpened():
    print("Error opening video file.")

(There is a main part - loop:)

name = 0
while video.isOpened():
    ret, frame = video.read()
        name += 1
        filename = f"{dir_stream}/{name}.jpg"
        cv.imwrite(filename, frame)
        f = cv.imread(filename)
        outp.write(f)

I don't like the way of saving the video... anyway - it's not completely wrong... it kind of works, but after few read frames (sometimes it's 153, 212 etc), ret value is returning False value and code gets into infinite loop. After I stopped the program, my video was saved and I could play it, it was just short (cause it was not recording as long as I wanted, because of infinite loop)...

In the "while" part I also tried...:

while video.isOpened():
        ret, frame = video.read()
        if ret:
            frame_r = cv.imread(frame)
            outp.write(frame_r)

... it's much more nice, but cv.imread(frame) was not working so I did it in dirty way u can see above.

My goal is recording online stream with python for some time (e.g. for 5 hours), I don't need record with 30fps, (e.g. 1fps is also fine). Can anyone help me with this problem? Or do you have some advice? Why ret value returns False after some random time? Do you have other solution? I'll be really thankful for your help, it's for my school project.

Upvotes: 0

Views: 2873

Answers (0)

Related Questions