安裝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()