我正在尝试使用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()
答案 0 :(得分:1)
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()
答案 1 :(得分:1)
问题是视频编解码器和视频容器格式不匹配。
执行代码时,我收到一条错误消息(在控制台窗口中):
OpenCV:FFMPEG:编解码器ID 15和格式“ mp4 / MP4(MPEG-4 Part 14)”不支持标签0x3234504d /'MP42''
[mp4 @ 00000155e95dcec0]在流#0中找不到编解码器msmpeg4v2的标签,容器中当前不支持编解码器
fourcc = cv2.VideoWriter_fourcc(*'MP42')
,并且M420
应用了视频编解码器 MPEG-4v2 。'output.mp4'
。.mp4
扩展名适用MP4容器格式。显然,.mp4
视频文件不能包含使用MPEG-4v2
编解码器编码的视频。
您可以更改编解码器或文件格式。
示例:
'output.avi'
或'output.wmv'
是可行的。 MPEG-4
:fourcc = cv2.VideoWriter_fourcc(*'mp4v')
(并保留文件名'output.mp4'
)也可以。又一个问题:
在ret, frame = cap.read()
之后添加以下代码:
if not ret:
break;