Nithin
Nithin

Reputation: 1477

Save grayscale video in OpenCV?

I am trying to save a video as .avi format but i keep getting the error "could not demultiplex stream". I primarily want to save grayscale videos.

Is there any specific codec i need to use?

Right now i tried with 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')

Upvotes: 16

Views: 25245

Answers (3)

vikash0837
vikash0837

Reputation: 31

There are 3 things to keep in mind when you are trying to write Grayscale image in video writer. 1. while reading the image,keep 0 followed by ','

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

2&3. While creating the video writer, declare shape in opposite way and keep 0 followed by ',' as we did in step 1

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

Upvotes: 3

bujikan
bujikan

Reputation: 316

For Windows OS try:

out = cv2.VideoWriter(outfilename, fourcc, fps, (width, height), 0)

Upvotes: 30

Saransh Kejriwal
Saransh Kejriwal

Reputation: 2533

It is possible that .DIVX is looking for a 3-channel BGR image to write, but you're only providing it a single channel image, since you're trying to write a grayscale image

Try doing this:

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

essentially this will try to convert your greyscale image to BGR image. While your pixel values will remain gray, this will change frame to a 3-channel image

Upvotes: 6

Related Questions