python - numpy.memmap 到 Image.frombuffer - 不复制

标签 python python-2.7 numpy python-imaging-library

我正在尝试内存映射在另一个进程中创建的文件以用作共享帧缓冲区。我不想复制数据,因为我想使用 PIL ImageDraw 函数来操作映射缓冲区,然后刷新更改。我对 python 和内存映射文件还很陌生。我错过了什么?

# 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()

最佳答案

我查看了 source code对于 frombuffer。原来它将 readonly 标志设置为 1。我不确定副作用,但如果您将标志设置为零,您的代码就可以工作:

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

关于python - numpy.memmap 到 Image.frombuffer - 不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640145/

相关文章:

python - 通过 Tweepy 去除推文中的换行符

parsing - 使用 dpkt 库从 DNS 响应数据包中提取域名

python - 脚本执行后保留命名空间和变量值

Python:为什么我的 POST 请求不起作用?

python - 了解自适应龙格库塔积分器的局部截断误差

python - 在多列上使用 Pandas df.where 会产生意外的 NaN 值

python-2.7 - 在 Python 中将彩色输出写入 CSV 文件

python - OpenCV Python-将一个图像放置在另一个图像之上

python - 实现与 numpy 一起使用的奇异复数

python - 从 3D numpy 数组中删除索引