0

I'm trying to use a couple of colormaps from matplotlib on a picture and save it afterwards. I tried a lot of stuff but i'm not able to just save it without the image beeing displaced by 1 or 2 pixels to the top. Also i feel like there are some slight mistakes in the proportions of the picture. The image is of size 64x64 Pixels.

I tried to experiment with dpi, and set dpi to 96(my screen dpi), 100 and 80. None of these worked. I got the 0.84 by experimenting to get 64x64 pixel output.

cmappsL1 = ["Paired", "Paired_r", "Spectral", "Spectral_r", "flag", "flag_r", "tab10"]
image = "example.png"
imgpath = "C:\\Users\\"

for i in range(len(cmapps)):
    fig = plt.figure(figsize=(0.84, 0.84)) #needed to get rid of padding
    ax = fig.add_subplot(1, 1, 1) #needed to get rid of pyplot padding
    plt.imshow(image, cmap=str(cmapps[i])) #use colormap
    plt.xticks([])#get rid of scale
    plt.yticks([])#get rid of scale
    ax.axes.get_xaxis().set_visible(False)#get rid of axis
    ax.axes.get_yaxis().set_visible(False)#get rid of axis
    ax.set_frame_on(False)#get rid of frame
    plt.savefig(imgpath+cmapps[i]+'.png', bbox_inches = 'tight', pad_inches = 0)
    plt.close(fig)

The generated pictures are slighty more to the top then the original image and also kind of perturbed. How to save the picture with a colormap so it has the exact propertys as the original except for the usage of the colormap?

Sphingidae
  • 13
  • 3

1 Answers1

0

It seems you do not need to create the figure at all, but can directly use imsave

cmappsL1 = ["Paired", "Paired_r", "Spectral", "Spectral_r", "flag", "flag_r", "tab10"]
image = plt.imread("example.png")

for i in range(len(cmapps)):
    plt.imsave(cmapps[i]+'.png', image, cmap=str(cmapps[i])) #use colormap

If instead you really want to create a figure without margins and padding, see Can't remove matplotlib's padding around imshow() figure or this answer. Key would be not to use bbox_inches = 'tight' and create a square figure, such that figsize*dpi == pixel dimensions.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712