首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不保存在opencv中的写入和读取视频

不保存在opencv中的写入和读取视频
EN

Stack Overflow用户
提问于 2022-02-25 06:33:47
回答 1查看 470关注 0票数 -1

我想在不保存视频的情况下,在用cv2.VideoWriter编写视频后阅读它。

例如:

代码语言:javascript
复制
video =  cv2.VideoWriter('using.mp4', cv2.VideoWriter_fourcc(*'MJPG'), 10, size)

现在,在编写这个cv2.VideoWriter对象之后,是否可以像video.read()一样读取它,但是因为read()cv2.VideoCapture的一个函数,它会抛出一个错误

代码语言:javascript
复制
Exception has occurred: AttributeError
'cv2.VideoWriter' object has no attribute 'read'

那么,有没有可能阅读cv2.VideoWriter

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-25 07:58:28

从视频写入器读取帧的替代方法是将帧保存在列表中,而不是保存循环中的每个帧。完成后,可以将它们写在循环之外,并将保存影响作为video.read()

代码语言:javascript
复制
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

详细的示例(注意,我更改了四me-您的示例不适合我)

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71261949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档