解决opencv输出视频无法正常播放问题

最近在利用opencv-python截取触发点时刻视频流的过程中遇到一个问题:利用opencv截取的视频片段无法正常播放。
上网查阅很多方法,花了很长时间才得以解决。
由查得的方法总结,可能存在的问题包括几方面:
1.编码方式不对
2.视频写入的图像尺寸与画布尺寸不对应

下面提供一段读取的代码,按照此格式改写自己的需求代码即可。

import numpy as np
import cv2

cap = cv2.VideoCapture('test.mp4')
fourcc = cv2.VideoWriter_fourcc(*'MJPG')

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print("width:",width, "height:", height)

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (width, height))

while (cap.isOpened()):
  ret, frame = cap.read()
  if ret == True:
    out.write(frame)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  else:
    break
    
cap.release()
out.release()
cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/weixin_48994268/article/details/114458138