I'm new to Python and Matplotlib, I would like to simply apply colormap to an image and write the resulting image, without using axes, labels, titles or anything usually automatically added by matplotlib. Here is what I did:
def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = plt.imshow(data)
fig.set_cmap('hot')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig(outputname)
It successfully removes the axis of the figure, but the figure saved presents a white padding and a frame around the actual image. How can I remove them (at least the white padding)? Thanks
No one mentioned
imsave
yet, which makes this a one-liner:It directly stores the image as it is, i.e. does not add any axes or border/padding.
I learned this trick from matehat, here:
yields
I think that the command
axis('off')
takes care of one of the problems more succinctly than changing each axis and the border separately. It still leaves the white space around the border however. Addingbbox_inches='tight'
to thesavefig
command almost gets you there, you can see in the example below that the white space left is much smaller, but still present.This should remove all padding and borders:
I liked ubuntu's answer, but it was not showing explicitly how to set the size for non-square images out-of-the-box, so I modified it for easy copy-paste:
Saving images without border is easy whatever dpi you choose if pixel_size/dpi=size is kept.
However displaying is spooky. If you choose small dpi, your image size can be larger than your screen and you get border during display. Nevertheless, this does not affect saving.
So for
The display becomes bordered (but saving works):
You can also specify the extent of the figure to the
bbox_inches
argument. This would get rid of the white padding around the figure.