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

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

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


当前回答

这对我去除虱子很有效:

fig, axes = plt.subplots(2, figsize=(15, 20))

for ax in axes:
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])

其他回答

还没有人提到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")

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

感谢大家的精彩回答……我也有同样的问题,想要绘制一个没有额外填充/空间等的图像,所以非常高兴能在这里找到每个人的想法。

除了没有填充的图像,我还希望能够轻松添加注释等,而不仅仅是一个简单的图像情节。

因此,我最终将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

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

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

被点赞的答案已经不管用了。让它工作,你需要 手动添加设置为[0,0,1,1]的轴,或删除图下的补丁。

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 5), dpi=20)
ax = plt.Axes(fig, [0., 0., 1., 1.])
fig.add_axes(ax)
plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")
plt.axis('off')                                # same as: ax.set_axis_off()

plt.savefig("test.png")

或者,你也可以把贴片去掉。不需要添加子图来删除填充。这是从下面Vlady的回答中简化出来的

fig = plt.figure(figsize=(5, 5))
fig.patch.set_visible(False)                   # turn off the patch

plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")
plt.axis('off')

plt.savefig("test.png", cmap='hot')

这是在2019/06/19用3.0.3版本测试的。图片见下图:

一个更简单的方法是使用pyplot.imsave。详情见luator的回答

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

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()