python - OpenCV VideoWriter 写入损坏的视频文件

我正在尝试使用如下所示的 Python 脚本从我的网络摄像头流式传输和保存视频,但出于某种原因,“myvideo.mp4”文件非常小,无法使用 QuickTime(或其他播放器)打开 -它似乎是空的。但是,视频流运行完美。

正如其他主题中所建议的那样,我尝试了不同的文件格式和编解码器,并传递了我的网络摄像头返回的精确 fps、宽度和高度。也许有人知道这里的问题是什么?提前致谢!

import cv2

cap = cv2.VideoCapture(0)

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fps = cap.get(cv2.CAP_PROP_FPS)

writer = cv2.VideoWriter('myvideo.mp4',cv2.VideoWriter_fourcc(*'mp4v'),fps,(width,height))

while True:

    ret,frame = cap.read()

    # OPERATIONS (DRAWING)
    writer.write(frame)    
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
writer.release()
cv2.destroyAllWindows()

我也曾尝试以 super 用户身份运行该脚本,但没有帮助。我正在使用 Mac。

QuickTime 错误:

无法打开文件“myvideo.mp4”。 该文件与 QuickTime Player 不兼容。

最佳答案

尝试更改fourcc(用于压缩帧的编解码器的4字符代码。)

writer = cv2.VideoWriter('myvideo.mp4',cv2.VideoWriter_fourcc(*'mp4v'),fps,(width,height))

替换为

writer = cv2.VideoWriter('myvideo.mp4',cv2.VideoWriter_fourcc(*'XVID'),fps,(width,height))

https://stackoverflow.com/questions/60318589/

相关文章:

c# - 使用 csc.exe 构建时访问内部异常

typescript - 当我尝试使用对象解构结果的变量时,TS 无法识别其类型

django - 使用 xlswriter || 自动调整列宽 Django

flutter - 有没有办法在 Flutter 中控制系统音乐?

python - BIGQUERY - 整数范围分区表中的未分区分区

google-cloud-storage - gcsfuse 不会写入文件夹

javascript - Jest/ react - TypeError : Cannot read

reactjs - 'react-hot-loader/babel' 是做什么用的?

angular - 使用 GitHub Actions 运行 Angular e2e 测试会抛出 "

python - Kivy Filechooser 在屏幕上滚动重叠文本