Python多進程可以拾取OpenCV視頻捕獲對象

更新時間:2024-03-12 15:52:48

問題闡述

我正在嘗試創建一個獨立的進程來處理從相機獲取的圖像。但多處理器似乎很難從OpenCV中提取視頻捕獲模塊🌞。有沒有人♍能推薦一種解決辦法?我使用的是python3.7.1

from multiprocessing import Process
import multiprocessing as mp
import time
import logging
import logging.handlers
import sys

import logging
from enum import Enum
import cv2


class Logger():
    @property
    def logger(self):
        component = "{}.{}".format(type(self).__module__, type(self).__name__)
        #default log handler to dump output to console

        return logging.getLogger(component)



class MyProcess(Logger):

    def __init__(self, ):
        self.process = Process(target = self.run, args=())
        self.exit = mp.Event()
        self.logger.info("initialize class")
        self.capture = cv2.VideoCapture(0)

    def run(self):
        while not self.exit.is_set():

            pass
        print("You exited!")

    def shutdown(self):
        print("Shutdown initiated")
        self.exit.set()


if __name__ == "__main__":
    p = MyProcess()
    p.process.start()
    print( "Waiting for a while")
    time.sleep(3)
    p.shutdown()
    time.sleep(3)
    print("Child process state: {}".format(p.process.is_alive())) 

返回錯誤說明無法對視頻捕獲對象進行酸洗。

文件"C:Program Files(X86)Microsoft Visual StudioSharedAnaconda3_64lib多處理Education tion.py",第60行,轉儲中 ForkingPickler(文件,協議).轉儲(Obj)

TypeError:無法Pickle cv2。視頻捕獲對象

精準答案

我不是專家,但我遇到了同樣的問題,我以這種方式解決了問題。

在init函數中不使用cv2.VideoCapture(0)

 def __init__(self, ):
    self.process = Process(target = self.run, args=())
    self.exit = mp.Event()
    self.logger.info("initialize class")
    self.capture = cv2.VideoCapture(0)

我移動了初始化以運行函數

 def run(self):
    self.capture = cv2.VideoCapture(0)
    while not self.exit.is_set():

它對我很管用。 也許它對你也有幫助