如何删除轴、图例和白色填充

2025-01-21 09:01:00
admin
原创
87
摘要:问题描述:我想将颜色图应用于图像并写入生成的图像,而不使用轴、标签、标题或 matplotlib 自动添加的任何内容。以下是我所做的:def make_image(inputname,outputname): data = mpimg.imread(inputname)[:,:,0] fig ...

问题描述:

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

它成功地删除了图形的轴,但保存的图形呈现出白色填充和实际图像周围的框架。

我怎样才能去除它们(至少是白色填充物)?


解决方案 1:

与单独更改每个轴和边框相比,该axis('off')方法更简洁地解决了其中一个问题。但是它仍然在边框周围留下了空白。添加bbox_inches='tight'命令savefig几乎可以让你到达那里;你可以在下面的例子中看到,剩下的空白要小得多,但仍然存在。

matplotlib 的较新版本可能需要bbox_inches=0而不是字符串'tight'(来自@episodeyang 和@kadrach)

from numpy import random
import matplotlib.pyplot as plt

data = random.random((5,5))
img = plt.imshow(data, interpolation='nearest')
img.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')

在此处输入图片描述

解决方案 2:

我从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')

产量

在此处输入图片描述

解决方案 3:

可能最简单的解决方案:

我只是将问题中描述的方法和Hooked的答案中的方法结合起来。

fig = plt.imshow(my_data)
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('pict.png', bbox_inches='tight', pad_inches = 0)

此代码后没有空格,也没有框架。

没有空格、轴或框架

解决方案 4:

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

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

在此处输入图片描述

解决方案 5:

plt.axis('off')

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

让我得到无边框的图像。

解决方案 6:

我发现这一切都有记录...

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

解决方案 7:

这应该删除所有填充和边框:

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)

解决方案 8:

被点赞的答案不再有效。要使其工作,您需要手动添加一个设置为 [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 的回答

解决方案 9:

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

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)

解决方案 10:

我喜欢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()

如果保持 pixel_size/dpi=size,无论您选择何种 dpi,都可以轻松保存无边框图像。

data = mpimg.imread('test.png')
save_image_fix_dpi(data, dpi=100)

在此处输入图片描述

但是显示效果很怪异。如果选择较小的 dpi,图像尺寸可能会大于屏幕,显示时会出现边框。不过,这并不影响保存。

因此对于

save_image_fix_dpi(data, dpi=20)

显示屏变得有边框(但可以保存):
在此处输入图片描述

解决方案 11:

这最终对我有用:

ax.margins(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()

解决方案 12:

这有效:

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

解决方案 13:

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

解决方案 14:

感谢大家的精彩回答......我遇到了完全相同的问题,只想绘制一张没有额外填充/空间等的图像,所以很高兴在这里找到大家的想法。

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

所以我最终将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

解决方案 15:

这对我消除蜱虫很有帮助:

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

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

解决方案 16:

我试过

plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.bottom'] = False
plt.rcParams['ytick.major.left'] = False
plt.rcParams['ytick.major.right'] = False
plt.rcParams['ytick.minor.left'] = False
plt.rcParams['ytick.minor.left'] = False
plt.rcParams['xtick.major.top'] = False
plt.rcParams['xtick.major.bottom'] = False
plt.rcParams['xtick.minor.top'] = False
plt.rcParams['xtick.minor.bottom'] = False
fig = plt.figure()

它会删除所有边框和轴。

我从Stack Overflow 上的另一个问题中了解到这一点。

解决方案 17:

我更喜欢这个解决方案,因为在我看来它是最干净的:

from numpy import random
import matplotlib.pyplot as plt

data = random.random((5,5))
fig,ax = plt.subplots()
ax.imshow(data)
ax.set_axis_off()

它提供了更多的控制,无需使用plt,并且只需要一行代码。

在此处输入图片描述

解决方案 18:

很惊讶这没有出现。要绘制 N 个图像,您可以使用:

N = 5
data_array = np.random.rand(15,15,N)
plt.figure(figsize=(5*N,5))
for i in np.arange(N):
    img = data_array[:,:,i]
    plt.subplot(1,N,i+1)
    plt.imshow(img)             # Generate image
    plt.axis("off")             # Remove axes
plt.tight_layout()              # Remove white space between images
plt.show()

产生类似

在此处输入图片描述

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1579  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1355  
  信创产品在政府采购中的占比分析随着信息技术的飞速发展以及国家对信息安全重视程度的不断提高,信创产业应运而生并迅速崛起。信创,即信息技术应用创新,旨在实现信息技术领域的自主可控,减少对国外技术的依赖,保障国家信息安全。政府采购作为推动信创产业发展的重要力量,其对信创产品的采购占比情况备受关注。这不仅关系到信创产业的发展前...
信创和国产化的区别   8  
  信创,即信息技术应用创新产业,旨在实现信息技术领域的自主可控,摆脱对国外技术的依赖。近年来,国货国用信创发展势头迅猛,在诸多领域取得了显著成果。这一发展趋势对科技创新产生了深远的推动作用,不仅提升了我国在信息技术领域的自主创新能力,还为经济社会的数字化转型提供了坚实支撑。信创推动核心技术突破信创产业的发展促使企业和科研...
信创工作   9  
  信创技术,即信息技术应用创新产业,旨在实现信息技术领域的自主可控与安全可靠。近年来,信创技术发展迅猛,对中小企业产生了深远的影响,带来了诸多不可忽视的价值。在数字化转型的浪潮中,中小企业面临着激烈的市场竞争和复杂多变的环境,信创技术的出现为它们提供了新的发展机遇和支撑。信创技术对中小企业的影响技术架构变革信创技术促使中...
信创国产化   8  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用