OpenCV学习笔记(2)——如何用OpenCV处理视频

时间:2022-11-23 23:32:17

如何用OpenCV处理视频

  • 读取视频文件,显示视频,保存视频文件
  • 从摄像头获取并显示视频

1.用摄像头捕获视频

  为了获取视频,需要创建一个VideoCapature对象。其参数可以是设备的索引号,也可以是一个视频文件。设备索引号一般笔记本自带的摄像头是0。之后就可以一帧一帧的捕获视频,但是一定要记得停止捕获视频

  # -*- coding:utf-8 -*-

import numpy as np
import cv2

cap = cv2.VideoCapture(0)#cap仅仅是摄像头的一个对象
while True:
ret,frame = cap.read()#一帧一帧的捕获视频,ret返回的是否读取成功,frame返回的是帧

# gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)#对帧的操作,这里是把彩色图像转为灰度图像
# cv2.imshow('frame',gray)

cv2.imshow('frame',frame)
if cv2.waitKey(1) == ord('q'):#key值写的太高,会导致视频帧数很低
break

print(ret)
cap.release()
cv2.destroyAllWindows()

cap.read()返回一个布尔值,如果帧的读取是正确的,就会返回True。可以通过检查他的返回值来查看视频文件是否已经到了结尾

有时候cap无法成功的初始化摄像头,此时需要用cap.isOpened()来检查是否初始化成功。返回值为True表示没有问题

可以用cap.get(propId)来获取视频的一些参数信息。propIdし0-18的整数,具体代表视频属性如下

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)

   某些值可以用cap.set(propId,value)来修改,value是想要设置的新值

 

2.从文件播放视频

  把摄像头捕获中的0改成视频文件就可以了。需要注意的是在播放视频时使用cv2.waiKey()设置适当的持续时间(帧间频率),如果设置的太低视频会播放的很快,太大又会播的太慢,一般设为25ms即可

  

3.保存视频

需要注意到地方都写在代码注释里了

# -*- coding:utf-8 -*-

import numpy as np
import cv2

cap = cv2.VideoCapture(0)#cap仅仅是摄像头的一个对象

fourcc = cv2.VideoWriter_fourcc(*'XVID')#指定编码格式,Windows使用XVID,注意该写法是固定的
out = cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))#定义一个视频存储对象,以及视频编码方式,帧率,视频大小格式,最后一项设定灰度图(默认为True彩色,但试了一下改成False视频生成会出错)

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) == ord('q'):
break
else:
break

cap.release()
out.release()
cv2.destroyAllWindows()