Angad Sandhu
Search
Browse
On this page

3.1_Numba_lab_2

Black and white

Now that we've had a look at multi-dimensional indexing why don't you try and use two-dimensional indexing to make our image black and white.

Instead of operating over all pixels channel by channel we want to just operate over all pixels and average the channels out.

Before you begin, please turn off Google Colab's autocompletion by going to the settings gear in the top right -> Editor -> Uncheck "Automatically trigger code completions"

import matplotlib as mpl
import matplotlib.pyplot as plt
from numba import cuda
import numpy as np
import math

plt.rcParams["figure.figsize"] = (30,4)

1. Load our image with matplotlib.

im = ...
plt.imshow(im)

2. Move our image to the GPU and create an output array of the same size.

gpu_im = ...
gpu_output = ...

3. Set our two-dimensional thead size and block size. Hint: Our threadsperblock should still multiply to 128.

threadsperblock = ...
blockspergrid_x = ...
blockspergrid_y = ...
blockspergrid = ...

4. Write our kernel.

@cuda.jit
def black_white(im, output):
    # With our two-dimensional grid we can get our index position in two dimensions
    x, y = ...

    # Because our grid is slightly larger than our image anything outside the image should be ignored
    if x < im.shape[0] and y < im.shape[1]:

        # Calculate the average across the RGB channels
        ...

        # Set all output RGB channels to the average
        ...

        # Pass the alpha channel through
        ...

5. Run the kernel.

...

6. Move the data back from the GPU and plot it.

plt.imshow(...)

Browse the library