I would like to apply colormap to an image, and write the resulting image, without using axes, labels, titles, or anything 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)?
Answers
To save the image without any padding or additional frame in matplotlib
, you can use the bbox_inches='tight'
option in the plt.savefig()
call and pad_inches=0
to remove the padding.
Also, to make sure that only the image is saved (without any axes, labels, or titles), it's better to use plt.axis('off')
to fully hide axes, and plt.gcf().set_size_inches
to control the figure size.
Here's how you can modify your code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def make_image(inputname, outputname):
data = mpimg.imread(inputname)[:, :, 0] # Read the image and take the first channel
plt.imshow(data, cmap='hot') # Apply colormap
plt.axis('off') # Hide axes
plt.gcf().set_size_inches((data.shape[1] / 100.0, data.shape[0] / 100.0)) # Set figure size based on image dimensions
plt.subplots_adjust(left=0, right=1, top=1, bottom=0) # Remove padding between image and edges
plt.savefig(outputname, bbox_inches='tight', pad_inches=0) # Save without padding
plt.close() # Close the figure to free memory
Explanation:
plt.axis('off')
: This hides all axes, labels, and ticks.plt.gcf().set_size_inches()
: Adjusts the size of the figure to match the dimensions of the image.plt.subplots_adjust()
: Sets the margins to zero to prevent any padding.bbox_inches='tight', pad_inches=0
: Ensures the saved image has no extra padding or borders.
This will save the image without the white padding and frame.