I'm trying to save videos from a movement detection system I built using OpenCv2 with Python on Ubuntu.
However, I'm only able to save the frames to a video file if I write the raw frames. If I try to transform it in any way, such as imutils.resize, or cv2.cvtColor it wont save.
Below is a snippet of the code that I'm using.
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
EDIT:
There were two errors in my code.
As highlighted by @Micka's comment, the gray scale image is 1-channel only and the VideoWriter was prepared to receive 3-channel images. I found out two ways to solve that. By configuring VideoWriter to work without colors or by changing the dimension of the image.
The second error was regarding VideoWrite's resolution. In the function imutils.resize I resized the image to (500,375), however, my VideoWriter was set to (1600,1200).
With all being said, below, the revised and working code.
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