4

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!

tylerthemiler
  • 5,496
  • 6
  • 32
  • 40
  • 1
    You're basically asking the same as [this other question](http://stackoverflow.com/questions/2578752/how-can-i-plot-nan-values-as-a-special-color-with-imshow-in-matplotlib), I guess. Could you give it a go? – Ricardo Cárdenes Jan 20 '12 at 00:57
  • Thanks! I googled this for at least an hour...idk how I didn't find that.... :( – tylerthemiler Jan 20 '12 at 23:15

2 Answers2

6

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

SpinUp __ A Davis
  • 5,016
  • 1
  • 30
  • 25
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • Ok, I am trying to show a perimeter, so I need the overlay on the inside of the figure to show the gradient you have up there. Which doesn't work. It plots blue where zero. Not sure what to do. – tylerthemiler Feb 24 '12 at 00:57
1

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.

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194