Reputation: 2777
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?
Upvotes: 1
Views: 204
Reputation: 606
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)
Upvotes: 2