首页 > 解决方案 > 转换图像后无法使用 cv2.VideoWriter 保存视频

问题描述

我正在尝试从我在 Ubuntu 上使用 OpenCv2 和 Python 构建的运动检测系统保存视频。

但是,如果我写入原始帧,我只能将帧保存到视频文件中。如果我尝试以任何方式对其进行转换,例如imutils.resizecv2.cvtColor它不会保存。

下面是我正在使用的代码片段。

fourcc = cv2.VideoWriter_fourcc(*'XVID')
outSecurity = cv2.VideoWriter(fileName+"security.avi",fourcc,20.0,(1600,1200))

while True:
    frame = vs.read()
    frame = frame[1]
    outSecurity.write(frame) #this frame is written to file

    frame = imutils.resize(frame, width=500)
    outSecurity.write(frame) #this frame IS NOT written to file

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)
    outSecurity.write(gray) #this frame IS NOT written to file
    

编辑:

我的代码中有两个错误。

  1. 正如@Micka 的评论所强调的那样,灰度图像只有 1 通道,而VideoWriter准备接收 3 通道图像。我找到了两种解决方法。通过将VideoWriter配置为在没有颜色的情况下工作或通过更改图像的尺寸。

  2. 第二个错误是关于VideoWrite 的分辨率。在函数imutils.resize中,我将图像大小调整为 (500,375),但是,我的VideoWriter设置为 (1600,1200)。

综上所述,下面是修改后的工作代码。

fourcc = cv2.VideoWriter_fourcc(*'XVID')
#VideoWriter accepting 1-channel images and fixing resolution
outGray = cv2.VideoWriter(fileName+"gray.avi",fourcc,20.0,(500,375),0)
#VideoWriter accepting 3-channel images and fixing resolution
outGeneral = cv2.VideoWriter(fileName+"general.avi",fourcc,20.0,(500,375))

while True:
    frame = vs.read()
    frame = frame[1]

    #Output image since resolution was fixed
    frame = imutils.resize(frame, width=500)
    outGeneral.write(frame) #this frame is written to file

    #Output image using VideoWriter only for 1-channel images
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)
    outGray.write(gray) #this frame is written to file

    #Change image to 3-channel version
    grey_temp = cv2.merge((gray,gray,gray))
    outGeneral.write(grey_temp) #this frame is written to file


标签: pythonopencvopencv-python

解决方案


推荐阅读