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

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

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


当前回答

您还可以将图形的范围指定为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)

其他回答

我发现这些都是有记录的……

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.axis.html#matplotlib.axes.Axes.axis

我的代码…“bcK”是512x512的映像

plt.figure()
plt.imshow(bck)
plt.axis("off")   # turns off axes
plt.axis("tight")  # gets rid of white border
plt.axis("image")  # square up the image instead of filling the "figure" space
plt.show()
plt.axis('off')

plt.savefig('example.png',bbox_inches='紧',pad_inches = 0)

让我得到无边界的图像。

我从matehat那里学到了这个技巧:

import matplotlib.pyplot as plt
import numpy as np

def make_image(data, outputname, size=(1, 1), dpi=80):
    fig = plt.figure()
    fig.set_size_inches(size)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    plt.set_cmap('hot')
    ax.imshow(data, aspect='equal')
    plt.savefig(outputname, dpi=dpi)

# data = mpimg.imread(inputname)[:,:,0]
data = np.arange(1,10).reshape((3, 3))

make_image(data, '/tmp/out.png')

收益率

我一直在寻找几个代码来解决这个问题,这个问题的验证答案是唯一帮助我的代码。

这对于散点图和三坐标图很有用。你所要做的就是把边距改为零,这样就完成了。

还没有人提到imsave,这就变成了一句话:

import matplotlib.pyplot as plt
import numpy as np

data = np.arange(10000).reshape((100, 100))
plt.imsave("/tmp/foo.png", data, format="png", cmap="hot")

它直接存储图像,即不添加任何轴或边界/填充。