Making image white space transparent, overlay onto imshow()

前端 未结 2 1736
遥遥无期
遥遥无期 2021-02-06 18:27

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 th

相关标签:
2条回答
  • 2021-02-06 19:20

    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)
    
    0 讨论(0)
  • 2021-02-06 19:23

    The easy way is to simply use your image as a background rather than an overlay. Other than that you will need to use PIL or Python Image Magic bindings to convert the selected colour to transparent.

    Don't forget you will probably also need to resize either your plot or your image so that they match in size.

    Update:

    If you follow the tutorial here with your image and then plot your data over it you should get what you need, note that the tutorial uses PIL so you will need that installed as well.

    0 讨论(0)
提交回复
热议问题