Array slicing

In the previous tutorial we converted an image to and from and surfarray object. This object is a 3D array, so all our processing will involve working with 3D arrays. The Pygame surfarray is does not work in quite the same way as normal Python arrays, but rather like numpy arrays. in this tutorial I will go over how to work with these arrays, so if you're familiar with numpy, this should all be very easy.

For this tutorial I will be using this example image (of a passion flower):

We can use the function defined in the previous tutorial to convert it into a surfarray object:

`pixels = getPixelArray('Passion_flower.jpg')`

Array indexing

In Python we normally index an array with pixels[n]. If we try this with our 3D array, it will return a 2D slice with dimensions (200 x 3) which represents the three RGB colour values for every pixel in the nth column in the image. If you set all the values in the 100th slice to 0 and save the image like so:

```pixels[100] = 0
saveSurface(pixels, 'Passion_flower_black_column.jpg')```

You get an image with all the pixels in the 100th column as black (0, 0, 0).

If we want a single value, we use three indices, separated by commas. For example, for my image pixels[50, 100, 0] returns 80. This tells us that the pixel 50 across, 100 down from the top left pixel has a red value of 80.

Array slicing

As with normal Python array slicing, we use colons to separate the start and stop value of a slice. For example:

```pixels = pixels[50:-50, 200:, :]
saveSurface(pixels, 'Passion_flower_crop.jpg')```

This creates a cropped image starting 50 pixels from the left to 50 pixels from the right, and starting 200 pixels from the top to the bottom; it includes all the colour information.

Array slicing with steps

Again, like normal Python arrays we can define a step for the slice with a second colon. For example:

```pixels = pixels[::2,::2,:]
saveSurface(pixels, 'Passion_flower_scale.jpg')```

This takes every second row of pixels and every second column of pixels and thus creates a scaled image: