关于opencv进行rtsp取流播放视频特别慢的问题记录
# coding:utf-8
import cv2
from matplotlib import pyplot as plt
from collections import deque
#通过cv2中的类获取视频流操作对象cap
#cap = cv2.VideoCapture('rtsp://Admin:111111@192.168.10.108:554/tcp/av0_0') #广州地铁取流
#cap = cv2.VideoCapture('rtsp://admin:abc.1234@192.168.1.64:554/tcp/av0_0') #海康威视摄像头取流
cap = cv2.VideoCapture('rtsp://admin:abc.1234@192.168.1.64:554:554/h264/ch4/main/av_stream') #海康威视摄像头取流
#cap = cv2.VideoCapture('rtsp://admin:abc.1234@192.168.1.64:554:554/Streaming/Channels/101') #海康威视摄像头取流
#cap = cv2.VideoCapture('rtsp://admin:abc.1234@192.168.1.108:554/cam/realmonitor?channel=1&subtype=0') #大华摄像头取流
#cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.2.110:554/tcp/av0_0') tx2取流
#cap = cv2.VideoCapture('rtsp://admin:123456@192.168.1.13:554/video1')#宇视
#调用cv2方法获取cap的视频帧(帧:每秒多少张图片)
#cap = cv2.VideoCapture(0)
fps = cap.get(cv2.CAP_PROP_FPS)
print(fps)
#获取cap视频流的每帧大小
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print(size)
#定义编码格式mpge-4
aa = deque(maxlen=5)
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')
#fourcc = cv2.VideoWriter_fourcc(*'avc1')
#定义视频文件输入对象
outVideo = cv2.VideoWriter('video/hkvision-04-23-1.avi',fourcc,fps,size)
#获取视频流打开状态
if cap.isOpened():
rval,frame = cap.read()
print('ture')
else:
rval = False
print('False')
tot=1
c=1
#循环使用cv2的read()方法读取视频帧
while rval:
rval,frame = cap.read()
#frame = cv2.resize(frame, (416,416))
#cv2.namedWindow('test', cv2.WINDOW_NORMAL)
#cv2.namedWindow('test', cv2.WINDOW_GUI_NORMAL)
cv2.imshow('test', frame)
#每间隔20帧保存一张图像帧
# if tot % 20 ==0 :
# cv2.imwrite('cut/'+'cut_'+str(c)+'.jpg',frame)
# c+=1
tot+=1
print('tot=',tot)
#使用VideoWriter类中的write(frame)方法,将图像帧写入视频文件
outVideo.write(frame)
cv2.waitKey(1)
cap.release()
outVideo.release()
cv2.destroyAllWindows()
使用以上视频进行取流大概有10秒左右的延时且容易崩溃,但是resize成小于(1914*1080)大小的图片就只有0.6秒的延时,并且很稳定
,后来发现将cv2.namedWindow注释后大约有一秒时间延时,基本满足要求