我想将颜色映射应用于图像,并写入结果图像,而不使用轴、标签、标题或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)

它成功地删除了图形的轴,但保存的图形显示了一个白色填充,以及实际图像周围的框架。

我如何删除它们(至少是白色填充)?


当前回答

这将删除所有的填充和边框:

from matplotlib import pyplot as plt

fig = plt.figure()
fig.patch.set_visible(False)

ax = fig.add_subplot(111)

plt.axis('off')
plt.imshow(data)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("../images/test.png", bbox_inches=extent)

其他回答

首先,对于某些图像格式(例如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)

您还可以将图形的范围指定为bbox_inch参数。这将消除图形周围的白色填充。

def make_image(inputname,outputname):
    data = mpimg.imread(inputname)[:,:,0]
    fig = plt.imshow(data)
    fig.set_cmap('hot')
    ax = fig.gca()
    ax.set_axis_off()
    ax.autoscale(False)
    extent = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted())
    plt.savefig(outputname, bbox_inches=extent)

这将删除所有的填充和边框:

from matplotlib import pyplot as plt

fig = plt.figure()
fig.patch.set_visible(False)

ax = fig.add_subplot(111)

plt.axis('off')
plt.imshow(data)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("../images/test.png", bbox_inches=extent)

如此:

    plot.axis('off')
    ax = plot.gca()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

这是最后对我有用的方法:

斧子。margin (x=0, y=0, tight=True)是关键行。

    fig = plt.figure(figsize=(8, 8))
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    ax.margins(x=0, y=0, tight=True)
    fig.add_axes(ax)
    for triangle in list_of_triangles:
        x_points = [point[0] for point in triangle]
        y_points = [point[1] for point in triangle]
        plt.fill(x_points, y_points, 'k', edgecolor='k')
    plt.savefig("test.png", bbox_inches=0, pad_inches=0)
    plt.show()