Making image white space transparent, overlay onto imshow()

matplotlib, python

Solution

With out your data, I can't test this, but something like

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

my_cmap = copy.copy(plt.cm.get_cmap('gray')) # get a copy of the gray color map
my_cmap.set_bad(alpha=0) # set how the colormap handles 'bad' values
lattice = plt.imread('path')
im = plt.imshow(data[0,:,:],vmin=v_min,vmax=v_max,extent=(0,32,0,32),interpolation='nearest',cmap='jet')

lattice[lattice< thresh] = np.nan # insert 'bad' values into your lattice (the white)

im2 = plt.imshow(lattice,extent=(0,32,0,32),cmap=my_cmap)

Alternately, you can hand `imshow` a NxMx4 `np.array` of RBGA values, that way you don't have to muck with the color map

im2 = np.zeros(lattice.shape + (4,))
im2[:, :, 3] = lattice # assuming lattice is already a bool array

imshow(im2)

Problem

I have a plot of spatial data that I display with imshow(). I need to be able to overlay the crystal lattice that produced the data. I have a png file of the lattice that loads as a black and white image.The parts of this image I want to overlay are the black lines that are the lattice and not see the white background between the lines. I'm thinking that I need to set the alphas for each background ( white ) pixel to transparent (0 ? ). I'm so new to this that I don't really know how to ask this question. EDIT: ``` import matplotlib.pyplot as plt import numpy as np lattice = plt.imread('path') im = plt.imshow(data[0,:,:],vmin=v_min,vmax=v_max,extent=(0,32,0,32),interpolation='nearest',cmap='jet') im2 = plt.imshow(lattice,extent=(0,32,0,32),cmap='gray') #thinking of making a mask for the white background mask = np.ma.masked_where( lattice < 1,lattice ) #confusion here b/c even tho theimage is gray scale in8, 0-255, the numpy array lattice 0-1.0 floats...? ```

Original source