OpenCV-python多程式實現兩個海康威視攝像頭同時錄入視訊(親測穩定分流無中斷)並儲存本地

Kenn@Wu發表於2020-09-26

OpenCV-python多程式實現兩個海康威視攝像頭同時錄入視訊(親測穩定分流無中斷)並儲存本地

最近做的一個專案需要用到兩個攝像頭同時讀取視訊錄入本地,進行解幀處理,網上搜尋的程式碼在自己的筆記本上不能穩定的錄入兩個攝像頭的視訊,幾分鐘就會報錯中斷(詳見文末參考),這邊在讀取視訊進行了調整和更改,測試可以穩定的讀取和儲存兩個攝像頭的視訊。

# 程式碼描述:利用多程式方法,利用兩個海康威視攝像頭,同時錄取視訊並儲存本地
# 
# 建立時間: 2020-09-26
# 建立人: Kenn Wu
# 修改時間:
# 版本:

import cv2
import time
import multiprocessing as mp


# 抓取圖片,確認視訊流的讀入
def image_put(q, name, pwd, ip, channel=101):
    cap = cv2.VideoCapture("rtsp://%s:%s@%s//Streaming/Channels/%d" \
                           % (name, pwd, ip, channel))
    # 獲取視訊幀率
    fps = cap.get(cv2.CAP_PROP_FPS)
    print('fps: ', fps)
    if cap.isOpened():
        print('HIKVISION1')
    else:
        cap = cv2.VideoCapture("rtsp://%s:%s@%s//Streaming/Channels/%d" \
                               % (name, pwd, ip, channel))
        fps = cap.get(cv2.CAP_PROP_FPS)
        print('fps: ', fps)
        print('HIKVISION2')

    while cap.isOpened():
        # print('cap.read()[0]:', cap.read()[0])
        ret, frame = cap.read()
        print('ret:', ret)
        frame = cv2.resize(frame, (1920, 1080))
        # 抓取圖片不成功再重新抓取
        if not ret:
            cap = cv2.VideoCapture("rtsp://%s:%s@%s//Streaming/Channels/%d" \
                                   % (name, pwd, ip, channel))
            print('HIKVISION2'
)
            ret, frame = cap.read()
            frame = cv2.resize(frame, (1920,1080))
        q.put(frame)
        # print('q.qsize():', q.qsize())
        q.get() if q.qsize() > 1 else time.sleep(0.01)


# 獲得視訊流幀數圖片,儲存讀入的視訊
def image_get(q, window_name):
    cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    # 視訊儲存路徑
    path = "D:/test/" + window_name + ".avi"       
    out = cv2.VideoWriter(path, fourcc, 20.0, (1920, 1080), True)
    while True:
        frame = q.get()
        out.write(frame)
        cv2.imshow(window_name, frame)
        cv2.waitKey(1)


# 解決程式問題
def run_multi_camera():
    # user_name, user_pwd = "admin", "password"
    user_name, user_pwd = "admin", "zhangxuexiang714"
    camera_ip_l = [
        "192.168.1.67",  # ipv4
        "192.168.1.64",
        # 把你的攝像頭的地址放到這裡,如果是ipv6,那麼需要加一箇中括號
    ]

    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=2) for _ in camera_ip_l]

    processes = []
    for queue, camera_ip in zip(queues, camera_ip_l):
        processes.append(mp.Process(target=image_put, args=(queue, user_name, user_pwd, camera_ip)))
        processes.append(mp.Process(target=image_get, args=(queue, camera_ip)))

    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()


if __name__ == '__main__':
    run_multi_camera()           # 呼叫主函式

提示:筆記本讀取的攝像頭網路IP地址需要自己設定好

參考文獻:

https://blog.csdn.net/ljx1400052550/article/details/106987943

相關文章