在OpenCV中保存灰度视频?

时间:2018-04-26 07:19:53

标签: python opencv

我正在尝试将视频保存为.avi格式,但我一直收到错误"could not demultiplex stream"。我主要想保存灰度视频。

我需要使用特定的codec吗?

现在我尝试使用XVID, DIVX

import imutils
import cv2
import numpy as np

interval = 30
outfilename = 'output.avi'
threshold=100.
fps = 10

cap = cv2.VideoCapture("video.mp4")

ret, frame = cap.read()
height, width, nchannels = frame.shape

fourcc = cv2.cv.CV_FOURCC(*'DIVX')
out = cv2.VideoWriter( outfilename,fourcc, fps, (width,height))

ret, frame = cap.read()
frame = imutils.resize(frame, width=500)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

while(True):

  frame0 = frame

  ret, frame = cap.read()
  frame = imutils.resize(frame, width=500)
  frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

  if not ret:
    deletedcount +=1
    break

  if np.sum( np.absolute(frame-frame0) )/np.size(frame) > threshold:
    out.write(frame)
  else:
    print "Deleted"

  cv2.imshow('Feed - Press "q" to exit',frame)

  key = cv2.waitKey(interval) & 0xFF

  if key == ord('q'):
    print('received key q' )
    break

cap.release()
out.release()
print('Successfully completed')

3 个答案:

答案 0 :(得分:4)

对于Windows操作系统,请尝试:

//make new check in
//load the document
XmlDocument checkInDoc = new XmlDocument();
checkInDoc.Load(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "checkIns.xml");

//create the nodes
XmlNode checkInNode = checkInDoc.CreateElement("CheckIn");
XmlNode nameNode = checkInDoc.CreateElement("Name");
XmlNode timeNode = checkInDoc.CreateElement("Time");

//assign values to the nodes
nameNode.InnerText = "New Check In";
timeNode.InnerText = "9:00 PM";

//place nodes in document and save
checkInNode.AppendChild(nameNode);
checkInNode.AppendChild(timeNode);
checkInDoc.DocumentElement.AppendChild(checkInNode);
checkInDoc.Save(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "checkIns.xml");

答案 1 :(得分:1)

.DIVX可能正在寻找要写入的3通道BGR图像,但您只提供单通道图像,因为您正在尝试编写灰度图像

尝试这样做:

frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)

基本上这会尝试将灰度图像转换为BGR图像。虽然您的像素值将保持灰色,但这会将frame更改为3通道图像

答案 2 :(得分:0)

当您尝试在视频编写器中编写灰度图像时,要记住三件事。 1.读取图像时,请保持0,后跟','

image = cv2.imread("data/PCB.jpg",0)

2&3。创建视频编写器时,以相反的方式声明形状并保持0      就像在步骤1中一样

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (image.shape[1],image.shape[0]),0)