Search code examples
pythonmatplotliblogarithmcolormap

Matplotlib imsave image with log norm


How could I save the image using the following colormap option using Matplotlib?

The current syntax doesn't allow me to do it?

plt.imsave('C:/Users/Desktop/Img/image'+'_'+ str(i)+'.png', data)

I would like to add this to above:

norm=matplotlib.colors.LogNorm()
cmap=my_cmap

Ideally I would like:

plt.imsave('C:/Users/Desktop/Img/image'+'_'+ str(i)+'.png', data, norm=matplotlib.colors.LogNorm(), cmap=my_cmap)

But this not possible.

Documentation of matplotlib.image.imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None, dpi=100)


Solution

  • Essentially using a LogNorm is the same as taking the logarithm of the data.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = plt.imread("house.png").mean(axis=2)
    logdata = np.log(data)
    plt.imsave("logimage.png", logdata, cmap="viridis")
    

    If some of the values are zero, it may not be obvious how a log plot should look like. You may replace zeros by nan values beforehands (this is what LogNorm would do)

    data[data == 0.] = np.nan
    logdata = np.log(data)
    

    or you may add a small amount to the data, such they are not zero any more

    logdata = np.log(data+0.02)