I have spent the last day or so looking at the interaction between PIL and numpy. PIL is useful for quickly loading and manipulating images (size, subsets etc) but if you really want to get to grips with image processing you need to understand numpy and the array structure. If you have come from Matlab then it can be a bit confusing as the syntax is “similar but different”. Anyway, here are some basic snippets of code:

```import Image as I # Import PIL
import numpy as N # Import Numpy
import pylab as P # Import Matplotlib functions
a = I.open("/home/al/Documents/temp_image_proc/bird/image4.jpg", "r") # Open the image
b = N.asarray(a) # Convert to Numpy array
red = b[:,:,0] # Extract red band
P.imshow(red) # Display the image
P.show()```

So we import the Image functions from PIL, numpy and the matplotlib plotting functions in pylab. Then we open up an image (.jpg format) convert it to an array, subset out the red band and display it. The image is shown here: Next, we need to know the dimensions of the image:

`red.shape`

Which returns the following: (3744, 5616). The numpy array can be sliced using the following code:

```fivelines = red[0:5] # slice 5 rows
P.plot(fivelines[1,:], fivelines[2,:], 'ko') # plot as black points all column values from rows 2 and 3
P.show()```

To extract rows one to three and columns five to nine of the array we need to use the code below. Essentially, it slices by the rows first, and then you need to state that all rows of columns x-y are required (hence the additional : in the columns part of the code:

`fivelines_sub = fivelines[0:3][:,4:9]`

To find the maximum value then use:

```fivelines.max()
>>>249```

To mask out certain values you need to do the following:

```red_mask = N.zeros((red.shape)) # create an array of 0 values the same size as the image to mask
red_index = N.nonzero(red > 150) # create an index of values over a threshold i.e. 150
red_mask[red_index, red_index] = 1 # convert indexed locations to a value of 1```

This will create a mask image: which can then be used to extract the values from the original image:

`temp = red*red_mask` 