2013-03-02 33 views
2

我正在尝试读取一系列.bmp图像,并根据我得到的提示做一些线性对比度调整。这些图像很小,112x112,我希望它们看起来完全一样,除了对比度调整。我试着用matplotlib来做这件事,但不管我做什么,我都会在图片的边框周围获得空白区域。这里是我使用的代码:从matplotlib中删除空格savefig

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

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

+0

相关:http://stackoverflow.com/questions/14503725/matplotlib-pyplot-imsave-backend/14506028#14506028 – tacaswell 2013-03-02 23:39:09

回答

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) 

这样,您就不必定义英寸的身材大小和DPI等等。您只需将PIL图像转换为numpy数组,进行一些数学运算并将其转换回PIL图像。

+0

我们可以做到这一点没有“图像”库吗?我没有在我的Python发行版中。 – 2016-05-11 16:20:27

+0

@JohnSmith:'Image'模块由PIL(或[Pillow](https://pypi.python.org/pypi/Pillow))包提供。有[阅读模块](https://pypi.python.org/pypi?%3Aaction=search&term=image+read&submit=search)用于阅读图片,如[imageio](http://imageio.readthedocs.io/en /latest/installation.html),尽管 - 免责声明 - 我从来没有使用它。一些图像格式,例如[PBM](https://en.wikipedia.org/wiki/Netpbm_format)非常简单,您可以编写自己的图像阅读器,但通常人们会安装PIL(或现在的枕头)来阅读图像。 – unutbu 2016-05-11 18:05:20

-1

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

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