Search code examples
pythonnumpyopencvmultiprocessingpickle

Multiprocessing manager can't pickle <class 'cv2.Mat'>


I made a multi-process program to analyze images from a camera. The first process constantly reads the image from the camera, the second analyzes this image, the third contains an HTTP server for returning the image. Frames are exchanged using multiprocessing.Manager.

import multiprocessing
import cv2

manager = multiprocessing.Manager()
frame = manager.Value(cv2.typing.MatLike, None)

The following code initializes a ValueProxy to exchange a frame between processes. This code works fine on my PC. However, when deploying this program on another machine, the following error occurs:

Traceback (most recent call last):
  File "/home/tablo/Apps/rvp-camera-service/src/main.py", line 7, in <module>
    camera_service = CameraService()
  File "/home/tablo/Apps/rvp-camera-service/src/camera_service.py", line 53, in __init__
    self.frame = self.manager.Value(cv2.typing.MatLike, None)
  File "/usr/lib/python3.10/multiprocessing/managers.py", line 723, in temp
    token, exp = self._create(typeid, *args, **kwds)
  File "/usr/lib/python3.10/multiprocessing/managers.py", line 608, in _create
    id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds)
  File "/usr/lib/python3.10/multiprocessing/managers.py", line 89, in dispatch
    c.send((id, methodname, args, kwds))
  File "/usr/lib/python3.10/multiprocessing/connection.py", line 206, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/lib/python3.10/multiprocessing/reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <class 'cv2.Mat'>: it's not the same object as cv2.Mat

Both systems have opencv 4.9.0 and python 3.10.6. So far I don’t understand why the behavior is different


Solution

  • What helped me was changing the first argument in the ValueProxy declaration (from cv2.typing.MatLike to cv2.Mat)