利用python多进程程或多线程的方式获取数据

两种方法均在自己电脑上测试(前提是要编译安装opencv),均可以通过代码如下:

1.python多进程实时读取数据

from multiprocessing import Queue, Process
import cv2
import datetime
#################################################
#摄像头地址
url = 'rtsp://admin:123@10.180.12.165'

def producer(q):
    cap = cv2.VideoCapture(url)
    while True:
        print('producer execuation')
        if cap.isOpened():
            ret, img = cap.read()
            q.put(img)


def consumer(q):
    while True:
        print("consumer execuation")
        img = q.get()

        if img is None:
            print("there is no img!")
            break

        width = int(img.shape[1])
        height = int(img.shape[0])
        time_stamp = datetime.datetime.now()
        date_now = time_stamp.strftime('%Y.%m.%d-%H:%M:%S')
        cv2.putText(img, date_now, (int(width / 20), int(height / 8)),cv2.FONT_HERSHEY_SIMPLEX, 4, (0, 255, 0), 10, cv2.LINE_AA)
        img_res = cv2.resize(img, (int(img.shape[1] / 3), int(img.shape[0] / 3)))

        cv2.imshow('img_multi_process', img_res)
        cv2.waitKey(1)

if __name__ == "__main__":
    q = Queue(maxsize=10) #设置对队列最大容量
    p1 = Process(target=producer, args=(q,))
    c1 = Process(target=consumer, args=(q,))
    p1.start()
    c1.start()

2.python多线程实时读取数据


import cv2
from threading import Thread
from collections import deque
import datetime
#################################################
# 摄像头地址
url = 'rtsp://admin:123@10.180.12.165'

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

def consumer(q):
    while True:
        if len(q) == 0:
            pass
        else:
            img = q.pop()
            print('consumer execuation')
            width = int(img.shape[1])
            height = int(img.shape[0])
            time_stamp = datetime.datetime.now()
            date_now = time_stamp.strftime('%Y.%m.%d-%H:%M:%S')
            cv2.putText(img, date_now, (int(width / 20), int(height / 8)),cv2.FONT_HERSHEY_SIMPLEX, 4, (0, 255, 0), 10, cv2.LINE_AA)
            img_res = cv2.resize(img, (int(img.shape[1] / 3), int(img.shape[0] / 3)))
            cv2.imshow('img_multi_process', img_res)
            cv2.waitKey(1)


if __name__ == '__main__':

    frame_deque = deque(maxlen=10)
    cap = cv2.VideoCapture(url)
    p1 = Thread(target=producer, args=(cap, frame_deque))
    p2 = Thread(target=consumer, args=(frame_deque,) )
    p1.start()
    p2.start()
    p1.join()
    p2.join()
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南洲.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值