The final example shows you how to mix NumPy operators with a tiny bit of filtering to get an interesting result. We start with a photo of a path in the forest:
im = mh.imread('forest')
To split the red, green, and blue channels, we use the following code. The NumPy transpose method changes the order of axes in a multi-dimensional array:
r,g,b = im.transpose(2,0,1)
Now, we filter the three channels separately and build a composite image out of it with mh.as_rgb. This function takes three two-dimensional arrays, performs contrast stretching to make each an 8-bit integer array, and then stacks them, returning a color RGB image:
r24 = mh.gaussian_filter(r, 24.) g24 = mh.gaussian_filter(g, 24.) b24 = mh.gaussian_filter(b, 24.) im24 = mh.as_rgb(r24, g24, b24)
Now, we blend the two images from the center away to the edges. First, we need to build a weights array W, which will contain at each pixel a normalized value, which is its distance to the center:
h, w = r.shape # height and width Y, X = np.mgrid[:h,:w]
We used the np.mgrid object, which returns arrays of size (h, w), with values corresponding to the y and x coordinates, respectively. The next steps are as follows:
Y = Y - h/2. # center at h/2 Y = Y / Y.max() # normalize to -1 .. +1 X = X - w/2. X = X / X.max()
We now use a Gaussian function to give the center region a high value:
C = np.exp(-2.*(X**2+ Y**2)) # Normalize again to 0..1 C = C - C.min() C = C / C.ptp() C = C[:,:,None] # This adds a dummy third dimension to C
Notice that all of these manipulations are performed using NumPy arrays and not some mahotas-specific methodology:
ringed = mh.stretch(im*C + (1-C)*im24)
Finally, we can combine the two images to have the center be in sharp focus and the edges softer: