python3.6 ,pyqt5获取海康录像机视频
1. python 获取摄像机视频
直接上代码
Channels: 录像机32通道,01主流码
transportmode:multicas多播,unicast单播
import cv2
import numpy as numpy
url = 'rtsp://13310:123456@172.31.2.7:554/Streaming/Channels/3201?transportmode=multicas'
cap=cv2.VideoCapture(url)
#设置显示分辨率和FPS ,不设置的话会非常卡
cap.set(cv2.CAP_PROP_FRAME_WIDTH,640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
cap.set (cv2.CAP_PROP_FPS,20)
while cap.isOpened():
ret,frame=cap.read()
#图像水平翻转
frame=cv2.flip(frame,0)
#图像是反的再换一次
frame=cv2.flip(frame,0)
cv2.imshow('camare',frame)
#按Q键退出
if cv2.waitKey(1) & 0xFF==ord('q'):
break
#释放摄像头和卸载窗口
cap.release()
cv2.destroyAllWindows()
2. pyqt5 获取摄像机视频
from PyQt5.QtGui import QPalette, QBrush, QPixmap
from PyQt5 import QtCore, QtGui, QtWidgets
import Ui_camera,sys,cv2,functools
class main(object):
"""docstring for main"""
def __init__(self,log=print):
super(main, self).__init__()
self.log=log
self.app = QtWidgets.QApplication(sys.argv)
self.GUI = QtWidgets.QMainWindow()
self.ui = Ui_camera.Ui_MainWindow()
self.ui.setupUi(self.GUI)
#摄像机配置
self.cameraConfig=self.get_camera_config()
#实例定时器
self.timer_camera = QtCore.QTimer()
#定时器超时执行
self.timer_camera.timeout.connect(self.show_camera)
#开启信号连接
self.ui.on.clicked.connect(functools.partial(self.open_camera,self.cameraConfig))
#关闭信号连接
self.ui.off.clicked.connect(self.close_camera)
#主循环
self.GUI.show()
sys.exit(self.app.exec_())
#获取摄像机配置
def get_camera_config(self,n=None):
n=n if n else 1
a={'user':13310,'password':123456,'host':'172.31.2.7','port':554,'channel':n,'mode':'multicas'}
return a
#显示视频
def show_camera(self):
# 读取图像
self.flag, self.image = self.cap.read()
#设置大小
show = cv2.resize(self.image, (480, 320))
#颜色
show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
#宽
img_with=show.shape[1]
#高
img_high=show.shape[0]
#读取数据转Qimage
showImage = QtGui.QImage(show.data, img_with, img_high,QtGui.QImage.Format_RGB888)
#设置标签的Qpixmap为读取的数据
self.ui.label.setPixmap(QtGui.QPixmap.fromImage(showImage))
#开启视频
def open_camera(self,config):
try:
#格式通道
config['channel']='%s01'%config.get('channel',1)
#海康摄像头RTSP地址
self.url = 'rtsp://{user}:{password}@{host}:{port}/Streaming/Channels/{channel}?transportmode={mode}'.format(**config)
#连接cv2连接到RTSP
self.cap=cv2.VideoCapture(self.url)
#设置并启动定时器
self.timer_camera.start(30)
except Exception as e:
self.log("启动摄像机失败,请检测网络连接或连接配置,异常:%s"%e,30)
#关闭视频
def close_camera(self):
#cv2是否连接
if self.cap.isOpened():
#断开
self.cap.release()
#定时器是否激活
if self.timer_camera.isActive():
#停止定时器
self.timer_camera.stop()
if __name__ == '__main__':
main()