无法在opencv中保存视频

Can't save a video in opencv

我正在尝试使用 opencv 写入方法保存我的视频,但视频保存为 0 kb。我的代码有什么问题。

  import cv2

  cap = cv2.VideoCapture("k1.mp4")
  fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
  fourcc = cv2.VideoWriter_fourcc(*'MP42')
  out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))

  while cap.isOpened():
     ret, frame = cap.read()
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     fgmask = fgbg.apply(gray)
     thresh = 2
     maxValue = 255
     ret, th1 = cv2.threshold(fgmask, thresh, maxValue, cv2.THRESH_BINARY)

     color_space = cv2.applyColorMap(th1, cv2.COLORMAP_JET)
     result_vid = cv2.addWeighted(frame, 0.7, color_space, 0.7, 0)
     cv2.imshow("vid", result_vid)
     out.write(result_vid)
     if cv2.waitKey(20) == ord('q'):
         break

 cap.release()
 out.release()
 cv2.destroyAllWindows()
 import cv2
 cap = cv2.VideoCapture(0)

 # Automatically grab width and height from video feed
 # (returns float which we need to convert to integer for later on!)
 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
 height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))


 # MACOS AND LINUX: *'XVID' (MacOS users may want to try VIDX as well just in case)
 # WINDOWS *'VIDX'
 writer = cv2.VideoWriter('local_capture.mp4', cv2.VideoWriter_fourcc(*'VIDX'),25, (width, height))


 # This loop keeps recording until you hit Q or escape the window
 # You may want to instead use some sort of timer, like from time import sleep and then just record for 5 seconds.
while True:

     # Capture frame-by-frame
     ret, frame = cap.read()


     # Write the video
     writer.write(frame)

     # Display the resulting frame
     cv2.imshow('frame',frame)

     # This command let's us quit with the "q" button on a keyboard.
     # Simply pressing X on the window won't work!
     if cv2.waitKey(1) & 0xFF == ord('q'):
         break
cap.release()
writer.release()
cv2.destroyAllWindows()

问题是视频 codec 和视频 container 格式不匹配。

执行您的代码时,我收到一条错误消息(在控制台中 windows):

OpenCV: FFMPEG: tag 0x3234504d/'MP42' is not supported with codec id 15 and format 'mp4 / MP4 (MPEG-4 Part 14)'
[mp4 @ 00000155e95dcec0] Could not find tag for codec msmpeg4v2 in stream #0, codec not currently supported in container

  • 您正在使用 fourcc = cv2.VideoWriter_fourcc(*'MP42')M420 应用视频编解码器 MPEG-4v2
  • 视频输出文件名为'output.mp4'
    .mp4 扩展应用 MP4 容器格式。

显然 .mp4 视频文件不能包含使用 MPEG-4v2 编解码器编码的视频。

您可以更改编解码器或更改文件格式。

示例:

  • 将输出文件名更改为 'output.avi''output.wmv' 有效。
  • 将编解码器更改为 MPEG-4fourcc = cv2.VideoWriter_fourcc(*'mp4v')(并保留文件名 'output.mp4')也有效。

还有一个问题:

ret, frame = cap.read()后添加如下代码:

if not ret:
    break;