简体   繁体   English

从matplotlib savefig删除空格

[英]Remove whitespace from matplotlib savefig

I'm trying to read in a series of .bmp images and do some linear contrast adjustment based on a tip I got. 我正在尝试阅读一系列.bmp图像,并根据获得的提示进行一些线性对比度调整。 These images are small, 112x112, and I want to them to come out looking exactly the same except contrast-adjusted. 这些图像很小,为112x112,我希望它们看起来完全一样,只是对比度调整过。 I've tried doing it with matplotlib, but no matter what I do I get white space around the border of the images. 我已经尝试过使用matplotlib进行此操作,但是无论我做什么,我都会在图像边框周围得到空白。 Here's the code I'm using: 这是我正在使用的代码:

# 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')

Any tips for how to remove the padding? 有关如何删除填充的任何提示? I've done some googling but nothing I've found has worked so far. 我已经进行了一些谷歌搜索,但是到目前为止,我发现仍然没有任何工作。

You can do thresholding without matplotlib: 您可以在没有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)

This way, you do not have to define a figure size in inches, and a DPI and so forth. 这样,您不必定义以英寸为单位的图形尺寸以及DPI等。 You just convert the PIL Image to a numpy array, do some math, and convert back to a PIL Image. 您只需将PIL图像转换为numpy数组,进行一些数学运算,然后再转换回PIL图像。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM