2.2.3.3 旧的buffer协议

In [9]:

  1. import numpy as np
  2. # import Image
  3. from PIL import Image
  4. # Let's make a sample image, RGBA format
  5. x = np.zeros((200, 200, 4), dtype=np.int8)
  6. x[:,:,0] = 254 # red
  7. x[:,:,3] = 255 # opaque
  8. data = x.view(np.int32) # Check that you understand why this is OK!
  9. img = Image.frombuffer("RGBA", (200, 200), data)
  10. img.save('test.png')
  11. #
  12. # Modify the original data, and save again.
  13. #
  14. # It turns out that PIL, which knows next to nothing about Numpy,
  15. # happily shares the same data.
  16. #
  17. x[:,:,1] = 254
  18. img.save('test2.png')
  1. /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/kernel/__main__.py:14: RuntimeWarning: the frombuffer defaults may change in a future release; for portability, change the call to read:
  2. frombuffer(mode, size, data, 'raw', mode, 0, 1)

2.2.3.3 旧的buffer协议 - 图12.2.3.3 旧的buffer协议 - 图2