简体   繁体   English

使用 opencv python 3 保存视频

[英]saving a video with opencv python 3

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.我使用带有 Python 3 和 Opencv 库的 jupyter 笔记本。

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()

The working video writer module of OpenCV depends on three main things: OpenCV 的工作视频写入器模块主要取决于三个方面:

  • 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输入视频分辨率应与 output 视频分辨率相同,否则在写入前调整帧大小

If any of this is wrong openCV will probably write a very small video file which will not open in video player.如果其中任何一个错误 openCV 可能会写入一个非常小的视频文件,该文件不会在视频播放器中打开。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM