在Python中使用OpenCV保存视频时出错[重复]

v6ylcynt  于 2023-10-24  发布在  Python
关注(0)|答案(1)|浏览(143)

此问题已在此处有答案

OpenCV videowrite doesn't write video(19回答)
上个月关门了。
考虑:

import cv2

cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('captured.mp3', fourcc, 20.0, (640, 640))

while(cam.isOpened()):
    ret, frame = cam.read()
    out.write(frame)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) == ord('e'):
        break
cam.release()
out.release
cv2.destroyAllWindows()

我得到一个错误,而保存此视频,如“视频类型不支持”。但我已经尝试了所有的文件类型的组合。仍然保存的视频是0 KB。

h6my8fg2

h6my8fg21#

  1. out. release后面缺少括号。
    1.“.mp3”通常用于音频文件,而“.mp4”用于视频文件。
    1.将“VideoWriter”分辨率设置为相机分辨率非常重要。
  2. MJPG编解码器不支持“.mp4”格式,因此您有两个选项-更改fourcc编解码器(例如,更改为“H264”),或将视频格式更改为“. avi”。
    选项1:
import cv2

cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'H264')
w = int(cam.get(3))
h = int(cam.get(4))
out = cv2.VideoWriter('captured.mp4', fourcc, 20, (w, h))

while cam.isOpened():
    ret, frame = cam.read()
    out.write(frame)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('e'):
        break
    
cam.release()
out.release()
cv2.destroyAllWindows()

选项2:

import cv2

cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
w = int(cam.get(3))
h = int(cam.get(4))
out = cv2.VideoWriter('captured.avi', fourcc, 20, (w, h))

while cam.isOpened():
    ret, frame = cam.read()
    out.write(frame)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('e'):
        break

cam.release()
out.release()
cv2.destroyAllWindows()

相关问题