Home > Net >  Writing and Reading video without saving in opencv
Writing and Reading video without saving in opencv

Time:02-26

I want to read a video after I write it with cv2.VideoWriter without saving the video.

For example:

video =  cv2.VideoWriter('using.mp4', cv2.VideoWriter_fourcc(*'MJPG'), 10, size)

Now, after writing this cv2.VideoWriter object, is it possible to read it likevideo.read(), but since read() is a function of cv2.VideoCapture and it will throw an error

Exception has occurred: AttributeError
'cv2.VideoWriter' object has no attribute 'read'

So, is there possible way of reading the cv2.VideoWriter?

CodePudding user response:

An alternative to reading frames from the video writer, is to save the frames in a list instead of saving each frame in the the loop. when you finished, you can write them outside the loop and have the save affect as video.read()

video =  cv2.VideoWriter('using.mp4', cv2.VideoWriter_fourcc(*'MJPG'), 10, size)
for frame in frames:
    writer.write(frame)
for frame in frames:
    # do other stuff here

detailed example (Notice i changed the fourcc - your example didnt work for me)

import cv2


def cam_test(port: int = 0) -> None:
    frames = []
    cap = cv2.VideoCapture(port)
    if not cap.isOpened():  # Check if the web cam is opened correctly
        print("failed to open cam")
    else:
        print('cam opened on port {}'.format(port))

        for i in range(10 ** 10):
            success, cv_frame = cap.read()
            if not success:
                print('failed to capture frame on iter {}'.format(i))
                break
            frames.append(cv_frame)
            cv2.imshow('Input', cv_frame)
            k = cv2.waitKey(1)
            if k == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()

    # Now you have the frames at hand

    if len(frames) > 0:
        # if you want to write them
        size = (frames[0].shape[1], frames[0].shape[0])
        video = cv2.VideoWriter(
            filename='using.mp4',
            fourcc=cv2.VideoWriter_fourcc(c1='m', c2='p', c3='4', c4='v'),
            fps=10,
            frameSize=size
        )
        for frame in frames:
            video.write(frame)

        # and to answer your question, you wanted to do video.read() which would have gave you frame by frame
        for frame in frames:
            pass  # each iteration is like video.read() if video.read() was possible

    return


if __name__ == '__main__':
    cam_test()

  • Related