我想将颜色映射应用于图像,并写入结果图像,而不使用轴、标签、标题或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)
它成功地删除了图形的轴,但保存的图形显示了一个白色填充,以及实际图像周围的框架。
我如何删除它们(至少是白色填充)?
我喜欢ubuntu的答案,但它没有明确地显示如何设置非方形图像的大小,所以我修改了它,以便于复制粘贴:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
def save_image_fix_dpi(data, dpi=100):
shape=np.shape(data)[0:2][::-1]
size = [float(i)/dpi for i in shape]
fig = plt.figure()
fig.set_size_inches(size)
ax = plt.Axes(fig,[0,0,1,1])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(data)
fig.savefig('out.png', dpi=dpi)
plt.show()
保存无边框的图像很容易,无论你选择什么dpi,如果pixel_size/dpi=size被保留。
data = mpimg.imread('test.png')
save_image_fix_dpi(data, dpi=100)
然而,展示是令人毛骨悚然的。如果你选择小的dpi,你的图像大小可以比你的屏幕大,你在显示时得到边框。然而,这并不影响储蓄。
因此,对于
save_image_fix_dpi(data, dpi=20)
显示变得有边框(但保存工作):
首先,对于某些图像格式(例如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)
感谢大家的精彩回答……我也有同样的问题,想要绘制一个没有额外填充/空间等的图像,所以非常高兴能在这里找到每个人的想法。
除了没有填充的图像,我还希望能够轻松添加注释等,而不仅仅是一个简单的图像情节。
因此,我最终将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