Slugging through array manipulation

Let's get some practice with numpy array manipulation by playing around with images.

Plotting images

To start, download the file linked here. If you look at the contents of this comma-separated variable file, you should see a gigantic array of integers separated by commas.

There are a bewildering multitude of options for loading a text file into an array. For now, let's go with np.loadtxt(), as shown below.

import numpy as np

img = np.loadtxt('banana_slug.csv', delimiter=',', dtype=int)

If we look at the documentation for np.loadtxt(), we see that the first argument is the path to the filename with the data, the first keyword used here says that we are reading comma-separated numbers, and the second keyword says that we want all of the numbers to be integers. Often when loading arbitrary data, we'll want to use the default value of dtype=float, but here when working with this particular image data, integers accurately represent the discretized data values.

Now let's plot the image using the imshow() function from matplotlib.pyplot.

from matplotlib import pyplot as plt


If everything loaded correctly, we should see an image (originally from Wikipedia) like the one shown below.

OG slug


Using your array indexing skills, make modified banana slug images as requested below. You may find it useful to review the numpy documentation. With the exception of the last two challenges, all of these can be completed with just one line, often with some tricky indexing.

Upside-down slug

Make a new image that flips the original image about the x-axis (up-to-down).

upside-down slug

Reversed slug

Make a new image that flips the original image about the y-axis (left-to-right).

reverse slug

Transposed slug

Make a new image that swaps the rows and columns of the original image.

transposed slug

Portrait slug

Sammy the Slug wants a nicely cropped portrait. Make a new image that crops out the left and right sides of the image.

portrait slug

Widescreen slug

Sammy the Slug is coming to you from a major motion picture that was filmed for widescreens and thus does not match the aspect ratio of your TV. Make an image like the one shown below that has a black bar on the top and bottom. You may want to make a copy (e.g., img_copy = img.copy()) of your original image before attempting to overwrite any values. With the default colormap and data values, 0 will produce the darkest shade.

star slug

Masked slug

Let's put all the focus at the center. Make a new image that only shows pixels in a circle around the slug's head. This is the trickiest challenge so far. You may find the np.indices() useful, and I would recommend looking into the documentation on boolean masks.

masked slug