Python cv2 读取rtsp视频流/USB摄像头并显示

安装python 库:
sudo apt install python-opencv

#!/bin/python
#### in rtsp server:
####  ffserver -f /etc/ffserver.conf &
#### ffmpeg -f v4l2 -i /dev/video0  -s 640x480 -r 24 -vcodec libx264 -an http://127.0.0.1:8090/feed1.ffm
import cv2

if __name__ == "__main__":
  cap = cv2.VideoCapture("rtsp://192.168.xx.xxx:8554/live1.h264")
  if cap.isOpened() :
    ret,frame=cap.read()
#    print "==== ret ===="
#    print ret
#    print "====print dir(frame)===="
#    print dir(frame)
#    print "====print frame.shape===="
#    print frame.shape
#    print "====print (frame.shape[0], frame.shape[1], frame.shape[2])===="
#    print (frame.shape[0], frame.shape[1], frame.shape[2])
#    print "====print frame.size===="
#    print frame.size
#    print "====print frame.data===="
#    #print frame.data
#    #print type(frame.data)
#    print "====print frame.copy===="
#    print frame.copy
#    print type(frame.copy)
#    print "====print frame.ctypes===="      
    #-------------------------------------------------------------------------------------------
    # !! frame.ctypes.data_as(c_char_p/c_void_p/...) 可以将python opencv读取到的图像转为
    #  C语言某种格式,在python传递参数给C语言的库时很有用。
    #  frame.ctypes.data_as(c_char_p):将一帧图像的内存地址转换为C语言char*型
    #-------------------------------------------------------------------------------------------
    print frame.ctypes
    print type(frame.ctypes)       
    print "====print frame.imag===="
    #print frame.imag
    #print type(frame.imag)
    print "====print frame.tobytes===="
    print frame.tobytes
    print type(frame.tobytes)
  
  ##cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,640)
  ##cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,480)
  while cap.isOpened():
    ret,frame=cap.read()
    print (frame.shape[0], frame.shape[1], frame.shape[2])
#    print ret
#    print dir(frame)
#    print frame.shape
#    print frame.size
#    print frame.data
    cv2.imshow("frame",frame)
    cv2.waitKey(10)

以上代码中注释部分大多为读取视频信息包括帧率,每帧图像大小,内容等信息的测试,下面为简单案例,
分别为读取USB摄像头数据和rtsp流数据,并显示:

import cv2 
if __name__ == "__main__":
  ## 读取rtsp视频流并显示
  cap = cv2.VideoCapture("rtsp://192.168.xx.xxx:8554/live1.h264")
  ## 读取usb-came 0(/dev/video0) 
  #cap = cv2.VideoCapture(0)
  while cap.isOpened():
    (ret,frame)=cap.read()
    print (frame.shape[0], frame.shape[1], frame.shape[2])
    cv2.imshow("frame",frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  cv2.destroyWindow("frame")
  cap.release()

你可能感兴趣的:(Python实现简单功能)