【问题标题】:numpy.memmap to Image.frombuffer - without copyingnumpy.memmap 到 Image.frombuffer - 无需复制
【发布时间】:2015-12-14 21:39:07
【问题描述】:

我正在尝试对在另一个进程中创建的文件进行内存映射,以用作共享帧缓冲区。我不想复制数据,因为我想使用 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()

【问题讨论】:

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


    【解决方案1】:

    我查看了source codefrombuffer。原来它将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
    

    【讨论】:

    • 谢谢。昨晚我注意到了,但我没有尝试强迫它。很高兴知道...我现在可以使用 pysdl。更多 C 代码以获得更好的性能。
    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2011-05-11
    • 2014-05-28
    • 2013-10-06
    • 2014-01-22
    相关资源
    最近更新 更多