前言
rtsp 為網路攝影機位置,
我們可以透過讀取,並即時顯示畫面,
做出一個類似播放器的效果。
在下面的範例程式碼中,
我們也提供了 平均 fps 計算 (全部 frame)、瞬時 fps 計算 (單一 frame)
sample code
import time
import cv2
video_path = "rtsp://user:[email protected]/h264"
SHOW_LIVEVIEW = True
SHOW_INFO_IN_TERMINAL = True
SHOW_INFO_IN_LIVEVIEW = True
def write_text(img, text):
# text = "FONT_HERSHEY_DUPLEX"
position = (20, 100)
font = cv2.FONT_HERSHEY_SIMPLEX
size = 1
color = (0, 255, 255)
thickness = 2
lineType = cv2.LINE_AA
cv2.putText(img, text, position, font, size, color, thickness, lineType)
return img
if __name__ == '__main__':
vid = cv2.VideoCapture(video_path)
Ts = time.time()
cnt = 0
before_time = 0
while(True):
img = vid.read()[1]
shape = img.shape
shape = (int(shape[1]), int(shape[0]))
cnt = cnt + 1
time_pass = time.time()-Ts
info_text = "Time: {:.2f}, Frame count: {:08d}, fps: {:.2f}, fps_one: {:.2f}".format(time_pass, cnt, cnt/time_pass, 1/(time_pass-before_time))
if SHOW_INFO_IN_LIVEVIEW:
img = write_text(img, info_text)
if SHOW_INFO_IN_TERMINAL:
print(f"\r{info_text}", end = "")
before_time = time.time()-Ts
img = cv2.resize(img, shape, interpolation=cv2.INTER_CUBIC)
if SHOW_LIVEVIEW:
img = cv2.resize(img, shape, interpolation=cv2.INTER_CUBIC)
cv2.namedWindow('rtsp', cv2.WINDOW_NORMAL)
cv2.resizeWindow('rtsp', shape[0], shape[1])
cv2.imshow('rtsp', img)
cv2.waitKey(1)
說明
我自己設計的可控制部份
在程式碼一開始部份:
- video_path:設定 rtsp 位置,user, password 請自行設置,另外 rtsp 路徑請自行確認
- SHOW_LIVEVIEW:是否在螢幕上顯示 rtsp 的即時畫面 (透過 imshow)
- SHOW_INFO_IN_TERMINAL:是否顯示資訊在終端機 (terminal) 上
- SHOW_INFO_IN_LIVEVIEW:是否顯示資訊在螢幕畫面 (需搭配 SHOW_LIVEVIEW 使用) 上
OpenCV 的可控制部份
rtsp 讀取邏輯
vid = cv2.VideoCapture(video_path)
while(True):
img = vid.read()[1]
其實沒有想像中那麼難,就單純從路徑直接 vid.read()[1],就可以直接拿一張圖片。
- 註:你可能會好奇,那 vid.read()[0] 是什麼?
vid.read() 會回傳兩個值,第一個值 (也就是 vid.read()[0] ) 是 True/False,代表有沒有取得畫面。
第二個值就是我們要的圖片囉! 所以我們才用 vid.read()[1] 直接拿取圖片,
不過我們也可以利用第一個值的概念,幫助我們判斷無法讀取 rtsp 的情況。
關於在螢幕上的 rtsp 即時畫面顯示,可以在這裡設定
cv2.namedWindow('rtsp', cv2.WINDOW_NORMAL)
cv2.resizeWindow('rtsp', shape[0], shape[1])
cv2.imshow('rtsp', img)
cv2.waitKey(1)
這邊是我自製的顯示 rtsp 畫面,詳細代表的設定意義如下:
- cv2.namedWindow:設定畫面名稱
- cv2.resizeWindow:修改畫面大小
- cv2.imshow:顯示畫面
- cv2.waitKey:保持畫面顯示