Home > Mobile >  saving a video with opencv python 3
saving a video with opencv python 3

Time:07-01

I want to save a video after converting to gray scale. I don't know where exactly put the line out.write(gray_video). I use jupyter notebook with Python 3, and the Opencv library.

the code is:

import cv2
import numpy as np

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

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('out_gray_scale.mp4', fourcc, 10.0, (640,  480),0)

while (True):
   (ret, frame) = video.read()

   if not ret:
       print("Video Completed")
       break

   # Convert the frames into Grayscaleo
   gray_video = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

   #writing
   gray_frame = cv2.flip(gray_video, 0)
   out.write(gray_video)  #it suppose to save the gray video

   #Show the binary frames
   if ret == True:
      cv2.imshow("video grayscale",gray_video)
    
      #out.write(gray_video)
      # Press q to exit the video  
      if cv2.waitKey(25) & 0xFF == ord('q'):
           break
   else:
       break
video.release()
cv2.destroyAllWindows()

CodePudding user response:

The working video writer module of OpenCV depends on three main things:

  • the available/supported/installed codecs on the OS
  • getting the right codec and file extension combinations
  • the input video resolution should be same as output video resolution otherwise resize the frames before writing

If any of this is wrong openCV will probably write a very small video file which will not open in video player. The following code should work fine:

import cv2
import numpy as np

video = cv2.VideoCapture("inp.mp4")
video_width  = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))   # float `width`
video_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))  # float `height`
video_fps = int(video.get(cv2.CAP_PROP_FPS))

print(video_width, video_height, video_fps)
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
out = cv2.VideoWriter('out_gray_scale1.avi', fourcc, video_fps, (video_width,  video_height),0)


while (True):
   ret, frame = video.read()

   if not ret:
       print("Video Completed")
       break

   # Convert the frames into Grayscale
   gray_video = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

   #Show the binary frames
   if ret == True:
      cv2.imshow("video grayscale",gray_video)

      #Writing video
      out.write(gray_video)

      # Press q to exit the video  
      if cv2.waitKey(25) & 0xFF == ord('q'):
           break
   else:
       break
video.release()
out.release()
cv2.destroyAllWindows()

CodePudding user response:

You did not say what the problem is, so I'm guessing the video file is unreadable.

You need to call out.release() when you're done. That writes some metadata/index structures to the video file.

If you don't do that, the video file will contain the data but it will be corrupted/unreadable.

  • Related