OpenCV VideoWriter

环境

Windows 11
python 3.12.2
opencv-contrib-python 4.9.0.80

保存视频问题

使用VideoWriter保存视频的时候结果只有1kb,显示文件已损坏。

解决方案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import cv2 as cv

# 创建采集object
cap = cv.VideoCapture('video.mp4') # 传入-1默认摄像头,也可是摄像头序号0/1/2,或视频文件名称

frame_height = cap.get(3)
frame_width = cap.get(4)
size = (frame_width, frame_height) # 使用VideoWriter时输出必须与输入同尺寸

writer = cv2.VideoWriter('out.mov', cv2.VideoWriter_fourcc(*'divx'), 25.5, size, isColor=True)
# 输出格式亲测.avi .mov .mp4可用
# fourcc参数divx和mp4v都可用
# 帧率可以是浮点数
# 尺寸是个与源视频同样大小的元组则可用,顺序为(宽,高)
# 如果对图像进行了灰度处理,必须修改isColor为False

while cap.isOpened():
ret, frame = cap.read()

if not ret:
print('can\'t recieve frame, exiting...')
break

#frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(frame)

cv2.imshow('frame', frame)

if cv2.waitKey(1) == ord('q'):
break

cap.release()
out.release()
cv2.destroyAllWindows()