• opencv-python cv2读写视频,灰度图像视频保存


    【问题】

    保存出来的视频只有1KB,或者6KB,读取生成的视频发现根本没有数据进来。

    【解决方案】

    网上说是因为宽度和高度互相换了,尝试之后发现并没有改变什么。

    找了半天发现,主要原因是因为灰度图像的扩充, 要么交给cv2.VideoWriter扩充,要么自己扩充,不要同时搞!不要同时搞!不要同时搞!

    1、读取视频

    给定视频路径,输出三维数组,宽度,高度,帧率,帧数

    1. def read_video(input_video_path):
    2. capture = cv2.VideoCapture(input_video_path)
    3. frame_width = int(capture.get(3)) # 输入视频的宽度
    4. frame_height = int(capture.get(4)) # 输入视频的高度
    5. fps = int(capture.get(5))
    6. num_frames = int(capture.get(7))
    7. frames = []
    8. while True:
    9. ret, tmp_frame = capture.read()
    10. if not ret:
    11. break
    12. frame = cv2.cvtColor(tmp_frame, cv2.COLOR_RGB2GRAY)
    13. frames.append(frame)
    14. capture.release()
    15. res = np.array(frames) # shape: (frame, height, width)
    16. return res, frame_width, frame_height, fps, num_frames
    frames, frame_width, frame_height, fps, num_frames = read_video(input_video_path)

    2、保存视频

    给定三维数组,保存成视频

    Version1(灰度图像也交给cv2.VideoWriter进行扩充, 自己不操作)

    1. def save_video(frames, output_video_path, frame_rate=30.0, is_color=False, codec='XVID'):
    2. frame_height, frame_width = frames.shape[1], frames.shape[2]
    3. fourcc = cv2.VideoWriter_fourcc(*codec)
    4. out = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (frame_width, frame_height), isColor=is_color)
    5. for frame in frames:
    6. out.write(frame)
    7. out.release()
    8. print(f"Video saved as {output_video_path}")
    save_video(frames, output_video_path, frame_rate=fps, is_color=False, codec='XVID')

    Version2(灰度图象时,自己进行维度的扩充)

    1. def save_video(frames, output_video_path, frame_rate=30.0, is_color=False, codec='XVID'):
    2. frame_height, frame_width = frames.shape[1], frames.shape[2]
    3. fourcc = cv2.VideoWriter_fourcc(*codec)
    4. out = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (frame_width, frame_height))
    5. for frame in frames:
    6. if not is_color:
    7. frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
    8. out.write(frame)
    9. out.release()
    10. print(f"Video saved as {output_video_path}")
     save_video(frames, output_video_path, frame_rate=fps, is_color=False, codec='XVID')

    虽然这个问题实在是因为自己太粗心了,卡了好一会儿,但还是希望帮到和我类似问题的童鞋!!!!!

  • 相关阅读:
    【计算机网络】(谢希仁第八版)第三章课后习题答案
    常用编码格式整理
    OB_MYSQL UPDATE 优化案例
    通关宝典!Java 面试核心知识让你面试过,过,过!
    DJ8-2 主存储器的组织
    CG Magic分享3dmax软件安装与打开文件转圈圈怎么办?
    Java学习笔记15——类型转换(基本数据类型)
    林乐博士走进中国人民大学,讲述区块链的理解与实践
    设计一个填充工具完美解决前后端甩锅的问题了
    js中的sort排序
  • 原文地址:https://blog.csdn.net/weixin_52120741/article/details/133361469