【问题标题】:Remove whitespace from matplotlib savefig从 matplotlib savefig 中删除空格
【发布时间】:2023-03-18 20:40:02
【问题描述】:

我正在尝试读取一系列 .bmp 图像,并根据我得到的提示进行一些线性对比度调整。这些图像很小,112x112,我希望它们看起来完全一样,除了对比度调整。我试过用 matplotlib 来做,但无论我做什么,我都会在图像边界周围得到空白。这是我正在使用的代码:

# Open image and convert to array
oldImage = Image.open(f)
imageArray = np.array(oldImage)

# Preprocessing
vrange = stats.mquantiles(imageArray.flatten(),prob=[0.01,0.99])

# Plot and save
fig = plt.figure()
fig.set_size_inches(1,1)
fig.set_dpi(112)
plt.imshow(imageArray,cmap="gray",interpolation="Nearest",vmin=vrange[0],vmax=vrange[1]);
plt.axis('off')
plt.savefig(f[:-4] + "_adjusted.png", bbox_inches='tight')

关于如何删除填充的任何提示?我已经做了一些谷歌搜索,但到目前为止我发现没有任何工作。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您可以在没有 matplotlib 的情况下进行阈值处理:

import os
from PIL import Image
import numpy as np
import scipy.stats.mstats as mstats

f = os.path.expanduser('~/tmp/image.png')
name, ext = os.path.splitext(f)
out = name+"_adjusted.png"

oldImage = Image.open(f).convert('L')
imageArray = np.array(oldImage)

vmin, vmax = mstats.mquantiles(imageArray.flatten(), prob=[0.01,0.99])

np.clip(imageArray, vmin, vmax, out=imageArray)
imageArray = (imageArray-vmin)*255/(vmax-vmin)
img = Image.fromarray(imageArray.astype('uint8'), 'L')
img.save(out)

这样,您不必以英寸为单位定义图形大小和 DPI 等。您只需将 PIL 图像转换为 numpy 数组,进行一些数学运算,然后再转换回 PIL 图像。

【讨论】:

  • 我们可以在没有“图像”库的情况下做到这一点吗?我的 Python 发行版中没有。
  • @JohnSmith:Image 模块由 PIL(或 Pillow)包提供。有alternative modules 用于读取图像,例如imageio,不过——免责声明——我从未使用过它。一些图像格式,例如PBM,足够简单,您可以编写自己的图像阅读器,但通常人们安装 PIL(或现在的 Pillow)来读取图像。
【解决方案2】:

plt.savefig()之前添加以下行:

plt.subplots_adjust(0,0,1,1,0,0)

【讨论】:

  • 最有用的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 2022-11-12
  • 2018-09-29
  • 2012-02-19
  • 2018-01-12
相关资源
最近更新 更多