Creating a masked array

Masked arrays can be used to ignore missing or invalid data items. A MaskedArray function from the numpy.ma module is a subclass of ndarray, with a mask. In this recipe, we will use the Lena Soderberg image as data source, and pretend that some of this data is corrupt. At the end, we will plot the original image, log values of the original image, the masked array, and log values thereof.

How to do it...

Let's create the masked array.

  1. Create the masked array.

    In order to create a masked array, we need to specify a mask. Let's create a random mask. This mask has values, which are either zero or one:

    random_mask = numpy.random.randint(0, 2, size=lena.shape)
  2. Create a masked array.

    Using the mask in the previous step, create a masked array:

    masked_array = numpy.ma.array(lena, mask=random_mask)

The following is the complete code for this masked array tutorial:

import numpy
import scipy
import matplotlib.pyplot

lena = scipy.misc.lena()
random_mask = numpy.random.randint(0, 2, size=lena.shape)

matplotlib.pyplot.subplot(221)
matplotlib.pyplot.title("Original")
matplotlib.pyplot.imshow(lena)
matplotlib.pyplot.axis('off')

masked_array = numpy.ma.array(lena, mask=random_mask)
print masked_array

matplotlib.pyplot.subplot(222)
matplotlib.pyplot.title("Masked")
matplotlib.pyplot.imshow(masked_array)
matplotlib.pyplot.axis('off')

matplotlib.pyplot.subplot(223)
matplotlib.pyplot.title("Log")
matplotlib.pyplot.imshow(numpy.log(lena))
matplotlib.pyplot.axis('off')

matplotlib.pyplot.subplot(224)
matplotlib.pyplot.title("Log Masked")
matplotlib.pyplot.imshow(numpy.log(masked_array))
matplotlib.pyplot.axis('off')

matplotlib.pyplot.show()

The resulting images are shown in the following screenshot:

How to do it...

How it works...

We applied a random mask to NumPy arrays. This had the effect of ignoring the data corresponding to the mask. There is a whole range of masked array operations to be found in the numpy.ma module. In this tutorial, we only demonstrated how to create a masked array.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset