简体   繁体   English

无法使用 OpenCV python 保存视频

[英]Unable to save video using OpenCV python

I am new to Computer Vision, I started my journey of Image Processing by using Pillow and Skimage Library than I tried with opencv but when I am using opencv for video processing I am unable to save my video captured by system camera.我是计算机视觉的新手,我通过使用 Pillow 和 Skimage 库开始了我的图像处理之旅,而不是尝试使用 opencv 但是当我使用 opencv 进行视频处理时,我无法保存系统摄像头捕获的视频。

import cv2
import numpy as np
cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_write = cv2.VideoWriter('saved_out.avi', fourcc, 20.0, (640, 480))
while True:
    ret, frame = cam.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    video_write.write(frame)
    cv2.imshow('frame',frame)
    cv2.imshow('gray', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cam.release()
video_write.release()
cv2.destroyAllWindows()

Have you tried mp4v instead of xvid?您是否尝试过 mp4v 而不是 xvid? The following works for me (windows):以下适用于我(Windows):

writer = cv2.VideoWriter('out.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 20, shape)

If this doesn't work you can also try:如果这不起作用,您还可以尝试:

  1. Don't hard code the video dimensions, use frame.shape instead to make sure the dimension match.不要对视频尺寸进行硬编码,而是使用 frame.shape 来确保尺寸匹配。 If they don't the writer cannot write the frame.如果他们不这样做,作者就无法编写框架。

    ret, frame = video.read() height, width = frame.shape[:2] shape = (width, height) video_write = cv2.VideoWriter('saved_out.avi', fourcc, 20.0, shape) ret, frame = video.read() height, width = frame.shape[:2] shape = (width, height) video_write = cv2.VideoWriter('saved_out.avi',fourcc, 20.0, shape)

IMPORTANT: if you are creating a frame from a np array, remember that width and height are inverted.重要提示:如果您从 np 数组创建框架,请记住宽度和高度是倒置的。 I lost 2 hours on a Saturday debugging this on my code.星期六我在我的代码上调试了 2 个小时。

newFrame = np.zeros((height, width), dtype='uint8')
  1. The frame needs to be in BGR format (3 channels).帧需要采用 BGR 格式(3 个通道)。 If grayscale image is used, you must pass the flag False for color when instantiating your writer object, like so:如果使用灰度图像,则在实例化您的编写器 object 时必须将标志 False 传递给颜色,如下所示:

    writer = cv2.VideoWriter('out.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 20, shape, False) writer = cv2.VideoWriter('out.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 20, 形状, False)

Docs: VideoWriter(filename, fourcc, fps, size, is_color)文档:VideoWriter(文件名,fourcc,fps,大小,is_color)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM