多线程读取+多进程保存多路摄像头图像

项目需要对多路在线视频采集数据保存,利用自己之前的两篇博客:
(1)利用python多进程程或多线程实时读取远程IP摄像头视频
(2)Pyhon cv2.VideoWriter 保存视频
整合成如下代码,可以对多路网络摄像头图像实时采集并分别保存视频。或者自己改写代码,直接保存每路的实时图像也可以。
需要修改:
(1)multithread_run()中自己的图像尺寸和帧率(帧率不一定跟源码流帧率一致)
(2)主函数中的url,记得加上自己的帐号密码

from threading import Thread
from collections import deque
from multiprocessing import Process
import cv2
#####################################################


def producer(cap, q):
    while True:
        # print('producer execuation')
        if cap.isOpened():
            ret, img = cap.read()
            q.append(img)

def consumer(camera_index, outVideo, q):
    print("Start to capture and save video of camera {}...".format(camera_index))
    while True:
        if len(q) == 0:
            pass
        else:
            img = q.pop()
            # print('consumer execuation')
            img_res = cv2.resize(img, (int(img.shape[1] / 3), int(img.shape[0] / 3)))
            cv2.namedWindow("camera {}".format(camera_index),0)
            outVideo.write(img)
            cv2.imshow("camera {}".format(camera_index), img_res)
            cv2.waitKey(1)


def multithread_run(camera_index, url):
    # get size and fps of video
    width = 2560
    height = 1920
    fps = 25
    fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')

    # create VideoWriter for saving
    outVideo = cv2.VideoWriter('Video_save_{}.avi'.format(camera_index), fourcc, fps, (width, height))
    q = deque(maxlen=1)
    cap = cv2.VideoCapture(url)
    p1 = Thread(target=producer, args=(cap, q))
    c1 = Thread(target=consumer, args=(camera_index, outVideo, q))
    p1.start()
    c1.start()
    p1.join()
    c1.join()

if __name__ == "__main__":
    processes = []
    nloops = range(2)
	
	#Assume that the two camera IPs are 192.168.9.151 and 192.168.9.152
    url = 'rtsp://10.180.9.{}:554'
    # url = 'rtsp://admin:[email protected]'
    camera_index = 151

    for i in nloops:
        t = Process(target=multithread_run, args=(camera_index + i, url.format(camera_index + i)))
        processes.append(t)

    for i in nloops:
        processes[i].start()

    for i in nloops:
        processes[i].join()


你可能感兴趣的:(图像处理)