保存出来的视频只有1KB,或者6KB,读取生成的视频发现根本没有数据进来。
网上说是因为宽度和高度互相换了,尝试之后发现并没有改变什么。
找了半天发现,主要原因是因为灰度图像的扩充, 要么交给cv2.VideoWriter扩充,要么自己扩充,不要同时搞!不要同时搞!不要同时搞!
给定视频路径,输出三维数组,宽度,高度,帧率,帧数
def read_video(input_video_path):
capture = cv2.VideoCapture(input_video_path)
frame_width = int(capture.get(3)) # 输入视频的宽度
frame_height = int(capture.get(4)) # 输入视频的高度
fps = int(capture.get(5))
num_frames = int(capture.get(7))
frames = []
while True:
ret, tmp_frame = capture.read()
if not ret:
break
frame = cv2.cvtColor(tmp_frame, cv2.COLOR_RGB2GRAY)
frames.append(frame)
capture.release()
res = np.array(frames) # shape: (frame, height, width)
return res, frame_width, frame_height, fps, num_frames
frames, frame_width, frame_height, fps, num_frames = read_video(input_video_path)
给定三维数组,保存成视频
def save_video(frames, output_video_path, frame_rate=30.0, is_color=False, codec='XVID'):
frame_height, frame_width = frames.shape[1], frames.shape[2]
fourcc = cv2.VideoWriter_fourcc(*codec)
out = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (frame_width, frame_height), isColor=is_color)
for frame in frames:
out.write(frame)
out.release()
print(f"Video saved as {output_video_path}")
save_video(frames, output_video_path, frame_rate=fps, is_color=False, codec='XVID')
def save_video(frames, output_video_path, frame_rate=30.0, is_color=False, codec='XVID'):
frame_height, frame_width = frames.shape[1], frames.shape[2]
fourcc = cv2.VideoWriter_fourcc(*codec)
out = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (frame_width, frame_height))
for frame in frames:
if not is_color:
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
out.write(frame)
out.release()
print(f"Video saved as {output_video_path}")
save_video(frames, output_video_path, frame_rate=fps, is_color=False, codec='XVID')
虽然这个问题实在是因为自己太粗心了,卡了好一会儿,但还是希望帮到和我类似问题的童鞋!!!!!