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

项目需要对多路在线视频采集数据保存,利用自己之前的两篇博客:
(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:12345@10.180.9.122'
    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()


  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南洲.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值