本文主要写两个功能,基于opencv视频的读取显视,以及视频的保存。
1、视频的读取
视频的读取这里主要讲三个方面的内容,分别摄像头,视频文件以及网络摄像头的rtsp
opencv是通过pip安装的,可以包含大部分的功能。
import cv2
print(cv2.__version__)
4.4.0
#读摄像头
url = 0 # 1或其它整数,表示摄像头的序号
#读视频文件
url = "test.mp4" #直接写文件的路径名就行
#读网络摄像头的rtsp
url="rtsp://用户名:密码@IP:端口号/h264/ch1/main/av_stream" # 主视频流
url="rtsp://用户名:密码@IP:端口号/h264/ch1/sub/av_stream" # 子视频流,比主视频流图像要小,解决网络不好等情况
cap= cv2.VideoCapture(url)#完成对相应内容的打开
2、视频的显示
有两种显示,一种是默认的显示方式,不可调大小;另一种是基于窗口的显示。所有内容以电脑本地摄像头为例
2.1 默认显示
import numpy as np
import cv2
cap=cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
#输出摄像头的信息
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
size =(width,height)
print("the size(w,h) of frame:{}".format(size))
print("the fps of the video:{}".format(fps))
while True:
#逐帧捕获
ret,frame=cap.read()
#如果正确读帧,ret为True
if not ret:
print("Can't receive frame (stream end?). Exiting...")
break
#do something to the frame
frame=cv2.flip(frame,1,dst=None)
cv2.imshow('frame',frame)
if cv2.waitKey(1) == ord('q') or cv2.waitKey(1) == ord('Q'):#按键q退出
break
#完成所有操作后,释放捕获器
cap.release()
cv2.destroyAllWindows()
the size(w,h) of frame:(640, 480)
the fps of the video:30.0
2.2带窗口显示
带窗口显示可以根据读取帧的大小,设定窗口,并可以全屏或鼠标调整显示大小
import numpy as np
import cv2
import time
WINDOW_NAME="Camera Demo"#窗口名字
cap=cv2.VideoCapture(0)
if not cap.isOpened():
print("摄像头打开失败,时间:",time.strftime("%Y年%m月%d日 %H:%M:%S",time.localtime()))
exit()
#输出摄像头的信息
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
size =(width,height)
print("the size(w,h) of frame:{}".format(size))
print("the fps of the video:{}".format(fps))
show_help = True
full_scrn = False
help_text = '"Esc" to Quit, "H" for Help, "F" to Toggle Fullscreen'
font = cv2.FONT_HERSHEY_PLAIN
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
cv2.resizeWindow(WINDOW_NAME, width, height)
cv2.moveWindow(WINDOW_NAME, 0, 0)
# cv2.setWindowTitle(WINDOW_NAME, 'Camera Demo1')#可以改窗口的名称
print("摄像头打开时间:",time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒'))
while True:
#逐帧捕获
if cv2.getWindowProperty(WINDOW_NAME, 0) < 0:
# Check to see if the user has closed the window
# If yes, terminate the program
break
ret,frame=cap.read()
#如果正确读帧,ret为True
if not ret:
print("Can't receive frame (stream end?). Exiting...")
print("摄像头读取失败,时间",time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒'))
break
if show_help:
cv2.putText(frame, help_text, (11, 20), font,
1.0, (32, 32, 32), 4, cv2.LINE_AA)
cv2.putText(frame, help_text, (10, 20), font,
1.0, (240, 240, 240), 1, cv2.LINE_AA)
#do something to the frame
cv2.imshow(WINDOW_NAME, frame)
key = cv2.waitKey(1)
if key == 27: # ESC key: quit program
print("摄像头关闭时间:",time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒'))
break
elif key == ord('H') or key == ord('h'): # toggle help message
show_help = not show_help
elif key == ord('F') or key == ord('f'): # toggle fullscreen
full_scrn = not full_scrn
if full_scrn:
cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN,
cv2.WINDOW_FULLSCREEN)
else:
cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN,
cv2.WINDOW_NORMAL)
#完成所有操作后,释放捕获器
cap.release()
cv2.destroyAllWindows()
the size(w,h) of frame:(640, 480)
the fps of the video:30.0
摄像头打开时间: 2020年09月12日 12时23分10秒
摄像头关闭时间: 2020年09月12日 12时24分24秒
3、视频的保存
视频在显示的同时,还可以进行保存,所在本节将结合第二节中视频的显示部分,在显示的同时完成视频保存
import numpy as np
import cv2
import time
WINDOW_NAME="Camera Demo"#窗口名字
cap=cv2.VideoCapture(0)
if not cap.isOpened():
print("摄像头打开失败,时间:",time.strftime("%Y年%m月%d日 %H:%M:%S",time.localtime()))
exit()
#输出摄像头的信息
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
size =(width,height)
print("the size(w,h) of frame:{}".format(size))
print("the fps of the video:{}".format(fps))
show_help = True
full_scrn = False
help_text = '"Esc" to Quit, "H" for Help, "F" to Toggle Fullscreen'
font = cv2.FONT_HERSHEY_PLAIN
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
cv2.resizeWindow(WINDOW_NAME, width, height)
cv2.moveWindow(WINDOW_NAME, 0, 0)
# cv2.setWindowTitle(WINDOW_NAME, 'Camera Demo1')#可以改窗口的名称
# 定义编解码器并创建VideoWriter对象
# fourcc = cv2.VideoWriter_fourcc(*'XVID') #输出avi视频
fourcc = cv2.VideoWriter_fourcc(*'mp4v') #输出MP4文件
#接着要进行视频保存
time_text =time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒')
output_path = "%s.mp4" % time_text
out = cv2.VideoWriter(output_path, fourcc, fps, size)
print("摄像头打开时间:",time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒'))
while True:
#逐帧捕获
if cv2.getWindowProperty(WINDOW_NAME, 0) < 0:
# Check to see if the user has closed the window
# If yes, terminate the program
break
ret,frame=cap.read()
#如果正确读帧,ret为True
if not ret:
print("Can't receive frame (stream end?). Exiting...")
print("摄像头读取失败,时间",time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒'))
break
if show_help:
cv2.putText(frame, help_text, (11, 20), font,
1.0, (32, 32, 32), 4, cv2.LINE_AA)
cv2.putText(frame, help_text, (10, 20), font,
1.0, (240, 240, 240), 1, cv2.LINE_AA)
#do something to the frame
out.write(frame)
cv2.imshow(WINDOW_NAME, frame)
key = cv2.waitKey(1)
if key == 27: # ESC key: quit program
print("摄像头关闭时间:",time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年', m='月', d='日', h='时', f='分', s='秒'))
break
elif key == ord('H') or key == ord('h'): # toggle help message
show_help = not show_help
elif key == ord('F') or key == ord('f'): # toggle fullscreen
full_scrn = not full_scrn
if full_scrn:
cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN,
cv2.WINDOW_FULLSCREEN)
else:
cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN,
cv2.WINDOW_NORMAL)
#完成所有操作后,释放捕获器
cap.release()
out.release()
cv2.destroyAllWindows()
the size(w,h) of frame:(640, 480)
the fps of the video:30.0
摄像头打开时间: 2020年09月12日 12时46分40秒
摄像头关闭时间: 2020年09月12日 12时47分18秒
本节在视频显示的同时,保存成mp4格式,至此,opencv对视频实现简单的使用。