python中的openCV视频保存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29317262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
openCV video saving in python
提问by
I am trying to save the video but it's not working. I followed the instructions from the openCV documentation.
我正在尝试保存视频,但它不起作用。我按照 openCV 文档中的说明进行操作。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
What is wrong?
怎么了?
采纳答案by Nurul Akter Towhid
Try this. It's working for me.
尝试这个。它对我有用。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
回答by Yasmin AM
I had the same problem and then I tried this:
我遇到了同样的问题,然后我尝试了这个:
frame = cv2.flip(frame,180)
instead of
代替
frame= cv2.flip(frame,0)
and it's working.
它正在工作。
回答by Bhanu Chander
Nuru answer actually works, only thing is remove this line frame = cv2.flip(frame,0)
under if ret==True:
loop which will output the video file without flipping
Nuru 答案实际上有效,唯一的问题是frame = cv2.flip(frame,0)
在if ret==True:
循环下 删除此行,它将输出视频文件而不翻转
回答by Naseeb Gill
I also faced same problem but it worked when I used 'MJPG'instead of 'XVID'
我也遇到了同样的问题,但是当我使用“MJPG”而不是'XVID'
I used
我用了
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
instead of
代替
fourcc = cv2.VideoWriter_fourcc(*'XVID')
回答by laurent thiol
As an example :
举个例子 :
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out_corner = cv2.VideoWriter('img_corner_1.avi',fourcc, 20.0, (640, 480))
At that place, have to define X,Y as width and height
在那个地方,必须将 X,Y 定义为宽度和高度
But, when you create an image (a blank image for instance) you have to define Y,X as height and width :
但是,当您创建图像(例如空白图像)时,您必须将 Y,X 定义为高度和宽度:
img_corner = np.zeros((480, 640, 3), np.uint8)
回答by Kershaw
jveitchmichaelis at https://github.com/ContinuumIO/anaconda-issues/issues/223provided a thorough answer. Here I copied his answer:
https://github.com/ContinuumIO/anaconda-issues/issues/223 上的jveitchmichaelis提供了详尽的答案。我在这里复制了他的回答:
The documentation in OpenCV says (hidden away) that you can only write to avi using OpenCV3. Whether that's true or not I've not been able to determine, but I've been unable to write to anything else.
However, OpenCV is mainly a computer vision library, not a video stream, codec and write one. Therefore, the developers tried to keep this part as simple as possible. Due to this OpenCV for video containers supports only the avi extension, its first version.
From: http://docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html
My setup: I built OpenCV 3 from source using MSVC 2015, including ffmpeg. I've also downloaded and installed XVID and openh264 from Cisco, which I added to my PATH. I'm running Anaconda Python 3. I also downloaded a recent build of ffmpeg and added the bin folder to my path, though that shouldn't make a difference as its baked into OpenCV.
I'm running in Win 10 64-bit.
This code seems to work fine on my computer. It will generate a video containing random static:
writer = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480)) for frame in range(1000): writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8')) writer.release()
Some things I've learned through trial and error:
- Only use '.avi', it's just a container, the codec is the important thing.
Be careful with specifying frame sizes. In the constructor you need to pass the frame size as (column, row) e.g. 640x480. However the array you pass in, is indexed as (row, column). See in the above example how it's switched?
If your input image has a different size to the VideoWriter, it will fail (often silently)
- Only pass in 8 bit images, manually cast your arrays if you have to (.astype('uint8'))
- In fact, never mind, just always cast. Even if you load in images using cv2.imread, you need to cast to uint8...
- MJPG will fail if you don't pass in a 3 channel, 8-bit image. I get an assertion failure for this at least.
- XVID also requires a 3 channel image but fails silently if you don't do this.
- H264 seems to be fine with a single channel image
- If you need raw output, say from a machine vision camera, you can use 'DIB '. 'RAW ' or an empty codec sometimes works. Oddly if I use DIB, I get an ffmpeg error, but the video is saved fine. If I use RAW, there isn't an error, but Windows Video player won't open it. All are fine in VLC.
In the end I think the key point is that OpenCV is not designed to be a video capture library - it doesn't even support sound. VideoWriter is useful, but 99% of the time you're better off saving all your images into a folder and using ffmpeg to turn them into a useful video.
OpenCV 中的文档说(隐藏起来)您只能使用 OpenCV3 写入 avi。我无法确定这是否属实,但我无法写任何其他内容。
但是OpenCV主要是一个计算机视觉库,不是视频流,编解码和写一个。因此,开发人员试图使这部分尽可能简单。由于这个用于视频容器的 OpenCV 仅支持 avi 扩展,它的第一个版本。
来自:http: //docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html
我的设置:我使用 MSVC 2015(包括 ffmpeg)从源代码构建了 OpenCV 3。我还从 Cisco 下载并安装了 XVID 和 openh264,并将它们添加到我的 PATH 中。我正在运行 Anaconda Python 3。我还下载了最新版本的 ffmpeg 并将 bin 文件夹添加到我的路径中,尽管这应该不会有什么不同,因为它已经融入了 OpenCV。
我在 Win 10 64 位上运行。
这段代码在我的电脑上似乎运行良好。它将生成一个包含随机静态的视频:
writer = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480)) for frame in range(1000): writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8')) writer.release()
我通过反复试验学到的一些东西:
- 只使用'.avi',它只是一个容器,编解码器很重要。
指定帧大小时要小心。在构造函数中,您需要将帧大小作为(列、行)传递,例如 640x480。但是,您传入的数组被索引为(行,列)。在上面的例子中看到它是如何切换的?
如果您的输入图像与 VideoWriter 的大小不同,它将失败(通常是静默的)
- 仅传入 8 位图像,如果必须,手动转换数组 (.astype('uint8'))
- 其实,没关系,只是一直在投。即使您使用 cv2.imread 加载图像,您也需要转换为 uint8...
- 如果您不传入 3 通道、8 位图像,MJPG 将失败。至少我得到了一个断言失败。
- XVID 还需要 3 通道图像,但如果您不这样做,则会静默失败。
- H264 似乎适合单通道图像
- 如果您需要原始输出,例如来自机器视觉相机,您可以使用“DIB”。'RAW' 或空的编解码器有时会起作用。奇怪的是,如果我使用 DIB,我会收到一个 ffmpeg 错误,但视频保存得很好。如果我使用 RAW,没有错误,但 Windows 视频播放器不会打开它。在 VLC 中一切都很好。
最后,我认为关键是 OpenCV 不是设计为视频捕获库 - 它甚至不支持声音。VideoWriter 很有用,但在 99% 的情况下,最好将所有图像保存到一个文件夹中并使用 ffmpeg 将它们转换为有用的视频。
回答by ????? ?????????
In my case, I found that size of Writer have to matched with the frame size both from camera or files. So that I read the frame size first and apply to writer setting as below.
就我而言,我发现 Writer 的大小必须与来自相机或文件的帧大小相匹配。所以我首先阅读帧大小并应用于如下的编写器设置。
(grabbed, frame) = camera.read()
fshape = frame.shape
fheight = fshape[0]
fwidth = fshape[1]
print fwidth , fheight
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (fwidth,fheight))
回答by zhengger
As @????? ????????? said: the sizes of Writer have to match with the frame from the camera or files.
作为 @?????????????? 说:Writer 的大小必须与来自相机或文件的框架相匹配。
You can use such code to check if your camera is (640, 480) or not:
您可以使用此类代码来检查您的相机是否为 (640, 480):
print(int(cap.get(3)), int(cap.get(4)))
For myself, I found my camera is (1280, 720) and replaced (640, 480) with (1280, 720). Then it can save videos.
对于我自己,我发现我的相机是 (1280, 720) 并用 (1280, 720) 替换了 (640, 480)。然后它可以保存视频。
回答by Dinusha Dilanka
Please make sure to set correct width and height. You can set it like bellow
请确保设置正确的宽度和高度。你可以像下面这样设置
cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))
回答by Boris
This is an answer was only tested in MacOS but it will probably also work in Linux and Windows.
这是一个仅在 MacOS 中测试过的答案,但它可能也适用于 Linux 和 Windows。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Get the Default resolutions
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
# Define the codec and filename.
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
# write the frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()