Book Image

NumPy Cookbook - Second Edition

By : Ivan Idris
Book Image

NumPy Cookbook - Second Edition

By: Ivan Idris

Overview of this book

<p>NumPy has the ability to give you speed and high productivity. High performance calculations can be done easily with clean and efficient code, and it allows you to execute complex algebraic and mathematical computations in no time.</p> <p>This book will give you a solid foundation in NumPy arrays and universal functions. Starting with the installation and configuration of IPython, you'll learn about advanced indexing and array concepts along with commonly used yet effective functions. You will then cover practical concepts such as image processing, special arrays, and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project with the help of examples. At the end of the book, you will study how to explore atmospheric pressure and its related techniques. By the time you finish this book, you'll be able to write clean and fast code with NumPy.</p>
Table of Contents (19 chapters)
NumPy Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using the buffer protocol


C-based Python objects have a so-called buffer interface. Python objects can expose their data for direct access without the need to copy it. The buffer protocol enables us to communicate with other pieces of Python software such as the Python Imaging Library (PIL).

We will see an example of saving a PIL image from a NumPy array.

Getting ready

Install PIL and SciPy if necessary. Check out the See also section of this recipe for instructions.

How to do it...

The complete code for this recipe is in the buffer.py file in this book's code bundle:

import numpy as np
import Image #from PIL import Image (Python 3)
import scipy.misc

lena = scipy.misc.lena()
data = np.zeros((lena.shape[0], lena.shape[1], 4), dtype=np.int8)
data[:,:,3] = lena.copy()
img = Image.frombuffer("RGBA", lena.shape, data, 'raw', "RGBA", 0, 1)
img.save('lena_frombuffer.png')

data[:,:,3] = 255 
data[:,:,0] = 222 
img.save('lena_modified.png')

First we need a NumPy array to play with:

  1. In previous chapters...