如何使用OpenCV VideoWriter将视频保存到特定目录-Python

时间:2019-12-07 14:09:19

标签: python python-3.x opencv video video-processing

我正在尝试将视频保存在特定的文件夹中。 但是运行代码后,不会保存任何输出。 有人可以帮忙吗?谢谢。

cap = cv2.VideoCapture(file_paths[0])
fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
name = "C:\jupyter_projects\Test Folder\Intention dataset\background_subtracted\out.mp4"
out = cv2.VideoWriter(name,fourcc, 20,(320,180),False)

while(1):
    ret, frame = cap.read()
    if (ret == True):
        resized_frame = cv2.resize(frame,(320,180),fx=0,fy=0, interpolation = cv2.INTER_CUBIC)
        fgmask = fgbg.apply(resized_frame)
        cv2.imshow('Frame',fgmask)
        out.write(fgmask)
        if cv2.waitKey(30) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.waitKey(5)
cv2.destroyAllWindows()

PS:当我使用默认目录保存视频时,将保存输出。

out = cv2.VideoWriter("out.mp4",fourcc, 20,(320,180),False)

4 个答案:

答案 0 :(得分:3)

尝试

fourcc = cv2.VideoWriter_fourcc(*'MP4V')

代替

fourcc = cv2.VideoWriter_fourcc(*'XVID')

答案 1 :(得分:2)

调用函数时

cv2.VideoWriter("/your/path/filename.mp4",fourcc, 20,(320,180))

我希望它会有所帮助:)

答案 2 :(得分:1)

使用createBackgroundSubtractorMOG2()

import cv2
cap = cv2.VideoCapture(0)
# fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
fgbg = cv2.createBackgroundSubtractorMOG2()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
name = "C://path//of//your_dir//out.mp4"
out = cv2.VideoWriter(name,fourcc, 20,(320,180),False)

while(1):
    ret, frame = cap.read()
    if (ret == True):
        resized_frame = cv2.resize(frame,(320,180),fx=0,fy=0, interpolation = cv2.INTER_CUBIC)
        fgmask = fgbg.apply(resized_frame)
        cv2.imshow('Frame',fgmask)
        out.write(fgmask)
        if cv2.waitKey(30) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.waitKey(5)
cv2.destroyAllWindows()

这将保存您的out.mp4给定位置。指定文件位置时,也可以使用单斜杠代替双斜杠。

答案 3 :(得分:-1)

尝试在文件目录中使用单引号和双斜杠。