1

I wrote this code to take a video file as input from my local storage, then display it and re-encode the frames in grayscale and save it to an output file. Here is my code:

import cv2 as cv

fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 25.0, (640,  480))
cap = cv.VideoCapture(input())
if not cap.isOpened():
    print("Error opening video file")
    exit()
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame. Exiting ...")
        break

    frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #This line is causing the problem
    out.write(frame)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break

cap.release()
out.release()
cv.destroyAllWindows()

With this code, I can see the video file being played, but the output file appears blank. It works if I write the original frame object into the output file. But, whenever I use frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) to convert the frame into grayscale, it does not work and I get a blank output file. What mistake am I doing?

1
  • Just a guess, and hence not an answer, but maybe your writer expects 3 channels rather than one. Try writing with out.write(np.dstack((frame,frame,frame))) Commented Jun 1, 2020 at 8:25

1 Answer 1

2

From the cv docs, here the signature of VideoWriter constructor is

VideoWriter (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)

i.e. if you're writing a grayscale image, you need to set the isColor param to false since it's true by default. Replace the line with this,

out = cv.VideoWriter('output.avi', fourcc, 25.0, (640,  480), 0)
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you are right, it works. Just one more question does the framesize parameter has to be equal to the original video size? Because if I give anything other than the original size, still I get a blank file output.
It needs to be equal to the size of each frame you're writing to the video. So doesn't have to be of the same size as the original. If you want a video of different frame size, make sure you resize each frame before writing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.