I'm trying to memory map a file created in another process to use as a shared frame buffer. I don't want the data copied because I want to use PIL ImageDraw functions to manipulate the mapped buffer, then flush the changes. I'm fairly new to python and memory mapped files. What am I missing?
# This is my setup code that creates a memory mapped array - seems to work
buf = np.memmap('/tmp/shared_mem', mode="readwrite", dtype="uint32", shape=(60,60))
# Here I build a PIL Image from the memory mapped data and correct layout, etc...
img = Image.frombuffer('RGBA', (60, 60), buf)
dr = ImageDraw.Draw(img)
# Changes using ImageDraw or putpixel do not show in the mapped file.
dr.rectangle(((0,0), (60,60)), fill="red")
buf.flush()
# Changes using numpy methods work just fine.
buf.fill(0)
buf.flush()
I had a look at the source code for frombuffer. Turns out it sets a readonly flag to 1. I'm not sure about the side-effects, but if you set the flag to zero your code works:
buf = np.memmap(fname, mode="readwrite", dtype="uint32", shape=(n,n))
buf[:] = 0
img = Image.frombuffer('RGBA', (n, n), buf)
img.readonly = 0
dr = ImageDraw.Draw(img)
dr.rectangle(((0,0), (n,n)), fill="red")
print buf[0,0]
# 4278190335
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With