选择图像区域(以编程方式!):Python 3,matplotlib

时间:2012-05-30 08:19:38

标签: python python-3.x matplotlib

我有一个图像,想要以某种方式得到一个新图像,它将是原始图像的矩形区域,以原始图像的中点为中心。比如说,原始图像是1000x1000像素,我想在原始图像的中心获得大小为501x501的区域。

使用Python 3和/或matplotlib进行任何操作?

2 个答案:

答案 0 :(得分:1)

PIL库中的image.crop方法似乎完成了任务: http://effbot.org/imagingbook/image.htm

例如:

br@ymir:~/temp$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Image
>>> im=Image.open('self.jpg')
>>> im.size
(180, 181)
>>> box=(10,10,100,100)
>>> im1=im.crop(box)
>>> im1.show()
>>> 

答案 1 :(得分:1)

目前还没有针对python 3的官方matplotlib版本(并且没有PIL)。

但是matplotlib dev应该兼容。

您可以使用matplotlib和numpy索引来实现此目的,而无需使用其他工具。 但是,matplotlib仅支持png natively

import matplotlib.pyplot as plt 
import matplotlib.image as mpimg
import matplotlib.cbook as mplcbook

lena = mplcbook.get_sample_data('lena.png')
# the shape of the image is 512x512
img = mpimg.imread(lena)

fig = plt.figure(figsize=(5.12, 5.12))

ax1 = plt.axes([0, 0, 1, 1], frameon=False)
ax1.imshow(img)

center = (300, 320) # center of the region
extent = (100, 100) # extend of the region
ax2 = plt.axes([0.01, 0.69, 0.3, 0.3])
img2 = img[(center[1] - extent[1]):(center[1] + extent[1]),
           (center[0] - extent[0]):(center[0] + extent[0]),:]
ax2.imshow(img2)
ax2.set_xticks([])
ax2.set_yticks([])
plt.savefig('lena.png', dpi=100)

lena.png