opencv教程2读取保存视频

5.1 用摄像头捕获视频
我们经常需要使用摄像头捕获实时图像。OpenCV 为这中应用提供了一个非常简单的接口。让我们使用摄像头来捕获一段视频,并把它转换成灰度视频显示出来。从这个简单的任务开始吧。
为了获取视频,你应该创建一个 VideoCapture 对象。他的参数可以是设备的索引号,或者是一个视频文件。设备索引号就是在指定要使用的摄像头。
一般的笔记本电脑都有内置摄像头。所以参数就是 0。你可以通过设置成 1 或者其他的来选择别的摄像头。之后,你就可以一帧一帧的捕获视频了。但是最
后,别忘了停止捕获视频。

 # -*- coding: utf-8 -*-
 """
 Created on Fri Jan 3 21:06:22 2014
 @author: duan
 """
 import numpy as np
 import cv2
 cap = cv2.VideoCapture(0)

 while(True):
 # Capture frame-by-frame
 ret, frame = cap.read()
 # Our operations on the frame come here
 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 # Display the resulting frame
cv2.imshow('frame',gray)
 if cv2.waitKey(1) & 0xFF == ord('q'):
 break
# When everything done, release the capture
 cap.release()
 cv2.destroyAllWindows()

cap.read() 返回一个布尔值(True/False)。如果帧读取的是正确的,就是 True。所以最后你可以通过检查他的返回值来查看视频文件是否已经到了结尾。有时 cap 可能不能成功的初始化摄像头设备。这种情况下上面的代码会报错。你可以使用 **cap.isOpened(),*来检查是否成功初始化了。如果返回值是True,那就没有问题。否则就要使用函数 cap.open()。你可以使用函数 cap.get(propId) 来获得视频的一些参数信息。这里
propId 可以是 0 到 18 之间的任何整数。每一个数代表视频的一个属性,见下表
其中的一些值可以使用 cap.set(propId,value) 来修改,value 就是你想要设置成的新值。
例如,我可以
使用 cap.get(3) 和 cap.get(4) 来查看每一帧的宽和高。*默认情况下得到的值是640X480。但是我可以使用

ret=cap.set(3,320)
ret=cap.set(4,240) 

来把宽和高改成 320X240。
注意:当你的程序报错时,你首先应该检查的是你的摄像头是否能够在其他程序中正常工作(比如 linux 下的 Cheese)。
5.2 从文件中播放视频
与从摄像头中捕获一样,你只需要把设备索引号改成视频文件的名字。在播放每一帧时,使用 cv2.waiKey() 设置适当的持续时间。如果设置的太低视频就会播放的非常快,如果设置的太高就会播放的很慢(你可以使用这种方法控制视频的播放速度)。通常情况下 25 毫秒就可以了。

• CV_CAP_PROP_POS_MSEC Current position of the video file
in milliseconds.
• CV_CAP_PROP_POS_FRAMES 0-based index of the frame to
be decoded/captured next.
• CV_CAP_PROP_POS_AVI_RATIO Relative position of the
video file: 0 - start of the film, 1 - end of the film.
• CV_CAP_PROP_FRAME_WIDTH Width of the frames in the
video stream.
• CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the
video stream.
• CV_CAP_PROP_FPS Frame rate.
• CV_CAP_PROP_FOURCC 4-character code of codec.
• CV_CAP_PROP_FRAME_COUNT Number of frames in the
video file.
• CV_CAP_PROP_FORMAT Format of the Mat objects returned
by retrieve() .
• CV_CAP_PROP_MODE Backend-specific value indicating the
current capture mode.
• CV_CAP_PROP_BRIGHTNESS Brightness of the image (only
for cameras).
• CV_CAP_PROP_CONTRAST Contrast of the image (only for
cameras).
• CV_CAP_PROP_SATURATION Saturation of the image (only
for cameras).
• CV_CAP_PROP_HUE Hue of the image (only for cameras).
• CV_CAP_PROP_GAIN Gain of the image (only for cameras).
• CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
• CV_CAP_PROP_CONVERT_RGB Boolean flags indicating
whether images should be converted to RGB.
• CV_CAP_PROP_WHITE_BALANCE Currently unsupported
• CV_CAP_PROP_RECTIFICATION Rectification flag for stereo
cameras (note: only supported by DC1394 v 2.x backend currently)
 # -*- coding: utf-8 -*-
 """
 Created on Fri Jan 3 21:06:22 2014
 @author: duan
 """
 import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
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)

# 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()

注意:你应该确保你已经装了合适版本的 ffmpeg 或者 gstreamer。如果你装错了那就比较头疼了。

3 保存视频
在我们捕获视频,并对每一帧都进行加工之后我们想要保存这个视频。对于图片来时很简单只需要使用 cv2.imwrite()。但对于视频来说就要多做点工作。
这次我们要创建一个 VideoWriter 的对象。我们应该确定一个输出文件的名字。接下来指定 FourCC 编码(下面会介绍)。播放频率和帧的大小也都需要确定。最后一个是 isColor 标签。如果是 True,每一帧就是彩色图,否则就是灰度图。FourCC 就是一个 4 字节码,用来确定视频的编码格式。可用的编码列表可以从fourcc.org查到。这是平台依赖的。下面这些编码器对我来说是有用个。
• In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is
more preferable. MJPG results in high size video. X264 gives
very small size video)
• In Windows: DIVX (More to be tested and added)
• In OSX : (I don’t have access to OSX. Can some one fill this?)
FourCC 码以下面的格式传给程序,以 MJPG 为例:
cv2.cv.FOURCC(‘M’,‘J’,‘P’,‘G’) 或者 cv2.cv.FOURCC(*‘MJPG’)。
下面的代码是从摄像头中捕获视频,沿水平方向旋转每一帧并保存它。

 # -*- coding: utf-8 -*-
 """
 Created on Fri Jan 3 21:06:22 2014
@author: duan
"""
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

 # Define the codec and create VideoWriter object
 fourcc = cv2.cv.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)

 # 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()

猜你喜欢

转载自blog.csdn.net/qq_43543515/article/details/115266348