使用open cv保存视频文件时出错

时间:2018-04-02 21:34:11

标签: python python-3.x opencv

程序:

import numpy as np
import cv2

cap = cv2.VideoCapture(1)
fourcc = cv2.VideoWriter_fourcc(*'VID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(True):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    out.write(frame)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

错误:

Traceback (most recent call last):
  File "D:/ANIKET/python projects/img_process.py", line 5, in <module>
    fourcc = cv2.VideoWriter_fourcc(*'VID')
TypeError: Required argument 'c4' (pos 4) not found

我正在尝试保存视频文件。 但是我得到了这个错误。 请告诉我我做错了什么

2 个答案:

答案 0 :(得分:1)

此代码解决了您的原始问题(将*'VID'替换为*'XVID')以及您对问题的评论中的后续问题:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret:
        gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY)

        out.write(gray)

        cv2.imshow('frame', gray)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()

请随意告诉我这是否符合您的预期,并指出任何遗留的问题!

答案 1 :(得分:0)

您也可以使用-1作为默认参数。它在我的案例中起作用了。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',-1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret:
        gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY)

        out.write(gray)

        cv2.imshow('frame', gray)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()