• 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')

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

  • 相关阅读:
    element ui框架(webpack打包器)
    【LeetCode】11. 盛最多水的容器
    树莓派4b+mcp2515实现CAN总线通讯和系统编程(一.配置树莓派CAN总线接口)
    Java 并发编程学习总结
    如何给Nginx配置访问IP白名单
    CenterNet算法by bilibili
    electron调用dll文件
    【Linux 从基础到进阶】自动化部署工具(Jenkins、GitLab CI/CD)
    【教程】OBS直播推流教程(Windows & macOS)
    【微信小程序】WXSS模板样式
  • 原文地址:https://blog.csdn.net/weixin_52120741/article/details/133361469