我一直在用Python从OpenCV摄像头读取图像,并从主程序读取最新的图像.这是因为硬件有问题.

在搞乱线程并获得非常低的效率(duh!)之后,我想切换到多处理.

以下是线程版本:

class WebcamStream:
    # initialization method
    def __init__(self, stream_id=0):
        self.stream_id = stream_id  # default is 0 for main camera

        # opening video capture stream
        self.camera = cv2.VideoCapture(self.stream_id)
        self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)
        self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 2880)

        if self.camera.isOpened() is False:
            print("[Exiting]: Error accessing webcam stream.")
            exit(0)

        # reading a single frame from camera stream for initializing
        _, self.frame = self.camera.read()

        # self.stopped is initialized to False
        self.stopped = True

        # thread instantiation
        self.t = Thread(target=self.update, args=())
        self.t.daemon = True  # daemon threads run in background

    # method to start thread
    def start(self):
        self.stopped = False
        self.t.start()

    # method passed to thread to read next available frame
    def update(self):
        while True:
            if self.stopped is True:
                break
            _, self.frame = self.camera.read()
        self.camera.release()

    # method to return latest read frame
    def read(self):
        return self.frame

    # method to stop reading frames
    def stop(self):
        self.stopped = True

以及-

if __name__ == "__main__":
    main_camera_stream = WebcamStream(stream_id=0)
    main_camera_stream.start()
    frame = main_camera_stream.read()

有人能帮我把这个翻译成多进程的土地吗?

谢谢

推荐答案

我已经为类似的问题写了几个解决方案,但已经有一段时间了,所以我们开始:

我将使用shared_memory作为缓冲区来读取帧,然后可以由另一个进程读取.我的第一个倾向是初始化相机并在子进程中读取帧,因为这似乎是一种"设置它然后忘记它"的事情.

import numpy as np
import cv2
from multiprocessing import Process, Queue
from multiprocessing.shared_memory import SharedMemory

def produce_frames(q):
    #get the first frame to calculate size of buffer
    cap = cv2.VideoCapture(0)
    success, frame = cap.read()
    shm = SharedMemory(create=True, size=frame.nbytes)
    framebuffer = np.ndarray(frame.shape, frame.dtype, buffer=shm.buf) #could also maybe use array.array instead of numpy, but I'm familiar with numpy
    q.put(shm) #send the buffer back to main
    q.put(frame.shape) #send the array details
    q.put(frame.dtype)
    try:
        while True:
            cap.read(framebuffer)
    except KeyboardInterrupt:
        pass
    finally:
        shm.close() #call this in all processes where the shm exists
        shm.unlink() #call this in at least one process

def consume_frames(q):
    shm = q.get() #get the shared buffer
    shape = q.get()
    dtype = q.get()
    framebuffer = np.ndarray(shape, dtype, buffer=shm.buf) #reconstruct the array
    try:
        while True:
            cv2.imshow("window title", framebuffer)
            cv2.waitKey(100)
    except KeyboardInterrupt:
        pass
    finally:
        shm.close()

if __name__ == "__main__":
    q = Queue()
    producer = Process(target=produce_frames, args=(q,))
    producer.start()
    consume_frames(q)

Python相关问答推荐

将numpy数组与空数组相加

替换字符串中的点/逗号,以便可以将其转换为浮动

Python主进程和分支进程如何共享gc信息?

实现的差异取决于计算出的表达是直接返回还是首先存储在变量中然后返回

如何在Python中使用io.BytesIO写入现有缓冲区?

Python Hashicorp Vault库hvac创建新的秘密版本,但从先前版本中删除了密钥

提取两行之间的标题的常规表达

如何使用Jinja语法在HTML中重定向期间传递变量?

删除最后一个pip安装的包

Python中的嵌套Ruby哈希

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

如何在Windows上用Python提取名称中带有逗号的文件?

形状弃用警告与组合多边形和多边形如何解决

如何更改groupby作用域以找到满足掩码条件的第一个值?

OpenGL仅渲染第二个三角形,第一个三角形不可见

Python—为什么我的代码返回一个TypeError

ModuleNotFoundError:没有模块名为x时try 运行我的代码''

Flask运行时无法在Python中打印到控制台

如何在Python请求中组合多个适配器?

如何强制向量中的特定元素在Gekko中处于优化解决方案中