从matplotlib的savefig中去除空白

2 投票
2 回答
2158 浏览
提问于 2025-04-17 17:43

我正在尝试读取一系列.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')

有没有什么建议可以去掉这些边距?我在网上查了很多资料,但到目前为止没有找到有效的方法。

2 个回答

0

plt.savefig()之前加上以下这一行:

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

你可以不使用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)

这样的话,你就不需要定义图像的尺寸、分辨率等参数了。你只需要把PIL图像转换成numpy数组,进行一些数学运算,然后再转换回PIL图像就可以了。

撰写回答