tylerthemiler
tylerthemiler

Reputation: 5766

Imoverlay in python

I am trying to overlay a matrix over another matrix using matplotlib imshow(). I want the overlay matrix to be red, and the "background matrix" to be bone, colormap wise. So, simply adding the images does not work, as you can only have one colormap. I have yet to find a different way to "overlay" besides just adding the matrices using imshow().

I am trying to, more or less, replace this matlab module.

Please let me know what alternatives I have!

Upvotes: 4

Views: 4923

Answers (2)

Joe Kington
Joe Kington

Reputation: 284890

Just use a masked array.

E.g.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.arange(100).reshape(10,10)
y = np.zeros((10,10))

# Make a region in y that we're interested in...
y[4:6, 1:8] = 1

y = np.ma.masked_where(y == 0, y)

plt.imshow(x, cmap=mpl.cm.bone)
plt.imshow(y, cmap=mpl.cm.jet_r, interpolation='nearest')

plt.show()

enter image description here

Upvotes: 6

mathematical.coffee
mathematical.coffee

Reputation: 56935

I tend to use OpenCV a lot which uses numpy as a backend, so images are just matrices.

To overlay a binary image onto a background image, you basically do:

overlaycolour = [255,0,0] # for red

for each channel c in 1:3
    overlayimage[:,:,c] = (1-alpha)*backgroundimage[:,:,c] + 
                              alpha*binary[:,:,c]*overlaycolour[c]

Here, alpha is the transparency of the overlay (if alpha is 1 the overlay is just pasted onto the image; if alpha is 0 the overlay is invisible, and if alpha is in between, the overlay is a bit transparent).

Also, either: - the binary image (ie image to be overlaid) is normalised to 1s and 0s and the overlay colour is from 0 to 255, OR - the binary image is 255s and 0s, and the overlay colour is from 0 to 1.

Finally if the background image is grey, turn it into a colour image by just replicating that single channel for each of the red, green, blue channels.

If you wanted to display your background image in a particular colour map you'll have to do that first and feed it in to the overlay function.

I'm not sure how this sort of code is done in PIL, but it shouldn't be too hard.

Upvotes: 1

Related Questions