转换图像后无法使用cv2.VideoWriter保存视频

时间:2020-07-07 14:28:05

标签: python opencv opencv-python

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

但是,如果我写原始帧,则只能将帧保存到视频文件中。如果我尝试以任何方式对其进行转换,例如 imutils.resize cv2.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


0 个答案:

没有答案