我想将颜色映射应用于图像,并写入结果图像,而不使用轴、标签、标题或matplotlib自动添加的任何内容。以下是我所做的:
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)
它成功地删除了图形的轴,但保存的图形显示了一个白色填充,以及实际图像周围的框架。
我如何删除它们(至少是白色填充)?
感谢大家的精彩回答……我也有同样的问题,想要绘制一个没有额外填充/空间等的图像,所以非常高兴能在这里找到每个人的想法。
除了没有填充的图像,我还希望能够轻松添加注释等,而不仅仅是一个简单的图像情节。
因此,我最终将David的回答与csnemes的回答结合起来,在图形创建时制作了一个简单的包装器。当你使用它时,你不需要对imsave()或其他任何东西进行任何更改:
def get_img_figure(image, dpi):
"""
Create a matplotlib (figure,axes) for an image (numpy array) setup so that
a) axes will span the entire figure (when saved no whitespace)
b) when saved the figure will have the same x/y resolution as the array,
with the dpi value you pass in.
Arguments:
image -- numpy 2d array
dpi -- dpi value that the figure should use
Returns: (figure, ax) tuple from plt.subplots
"""
# get required figure size in inches (reversed row/column order)
inches = image.shape[1]/dpi, image.shape[0]/dpi
# make figure with that size and a single axes
fig, ax = plt.subplots(figsize=inches, dpi=dpi)
# move axes to span entire figure area
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
return fig, ax
首先,对于某些图像格式(例如TIFF),你可以在标题中保存颜色图,大多数查看器会显示你的数据和颜色图。
为了保存实际的matplotlib图像,这对于向图像添加注释或其他数据非常有用,我使用了以下解决方案:
fig, ax = plt.subplots(figsize=inches)
ax.matshow(data) # or you can use also imshow
# add annotations or anything else
# The code below essentially moves your plot so that the upper
# left hand corner coincides with the upper left hand corner
# of the artist
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
# now generate a Bbox instance that is the same size as your
# single axis size (this bbox will only encompass your figure)
bbox = matplotlib.transforms.Bbox(((0, 0), inches))
# now you can save only the part of the figure with data
fig.savefig(savename, bbox_inches=bbox, **kwargs)