Skip to content

Instantly share code, notes, and snippets.

@kevinlinxc
Last active October 1, 2023 05:32
Show Gist options
  • Save kevinlinxc/80b895b514af0dcef53d49287f67f5d9 to your computer and use it in GitHub Desktop.
Save kevinlinxc/80b895b514af0dcef53d49287f67f5d9 to your computer and use it in GitHub Desktop.
Image transfer using shared memory in Python
import numpy as np
from multiprocessing import shared_memory
# Define global dimensions of 1080 video, would need to change this for a different camera resolution
w, h = 1920, 1080
class SharedMemImagePub:
def __init__(self):
# Create a named SharedMemory object
shm = shared_memory.SharedMemory(
create=True, name="image_pub", size=w * h * 3
)
# Create a Numpy array backed by the SharedMemory
self.im = np.ndarray((h, w, 3), dtype=np.uint8, buffer=shm.buf)
def publish_image(self, cv_image):
# important! self.im = cv_image would not work. We are filling the memory, not reassigning it.
self.im[:] = cv_image
class SharedMemImageSub:
def __init__(self):
self.existing_shm = shared_memory.SharedMemory(name="image_pub")
def read_image(self):
im = np.ndarray((h, w, 3), dtype=np.uint8, buffer=self.existing_shm.buf)
return im
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment