Book Image

NumPy Cookbook

Book Image

NumPy Cookbook

Overview of this book

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.
Table of Contents (17 chapters)
NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Loading images into memory map


It is recommended to load large files into memory maps. Memory-mapped files only load a small part of large files. NumPy memory maps are array-like. In this example, we will generate an image of colored squares and load it into a memory map.

Getting ready

If necessary, install Matplotlib. The See Also section of this recipe has a reference to the corresponding recipe.

How to do it...

We will begin by initializing arrays.

  1. First, we need to initialize the following arrays:

    • an array that holds the image data

    • an array with random coordinates of the centers of the squares

    • an array with random radii of the squares

    • an array with random colors of the squares

      img = numpy.zeros((N, N), numpy.uint8)
      centers = numpy.random.random_integers(0, N, size=(NSQUARES, 2))
      radii = numpy.random.randint(0, N/9, size=NSQUARES)
      colors = numpy.random.randint(100, 255, size=NSQUARES)

    Initialize the arrays as follows:

    As you can see, we are initializing the first array to zeroes. The other arrays...