python - 转换图像后无法使用 cv2.VideoWriter 保存视频
问题描述
我正在尝试从我在 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
编辑:
我的代码中有两个错误。
正如@Micka 的评论所强调的那样,灰度图像只有 1 通道,而VideoWriter准备接收 3 通道图像。我找到了两种解决方法。通过将VideoWriter配置为在没有颜色的情况下工作或通过更改图像的尺寸。
第二个错误是关于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
解决方案
推荐阅读
- eclipse - 在 pydev 中创建模板
- android - 三星互联网浏览器音频未播放
- javascript - 广告请求成功,但由于广告资源不足,未返回任何广告。处理AdFailedToLoad
- javascript - (ReactJS + Redux)将/new添加到url时表单不加载
- sed - sed/find/grep 如果不存在,则将 c# 注释附加到文件顶部,如果存在则替换
- ios - Swift iOS - 按属性比较 1 个数组中的元素
- css - 块引用列表中的样式链接
- angular - 如何访问角度 httpClient 状态属性作为响应
- html - 悬停时无序列表中的 HTML 链接不改变颜色
- java - Maven 找不到 JavaFX