1

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

使用 Python 3 和/或 matplotlib 有什么办法吗?

4

2 回答 2

2

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()
>>> 
于 2012-05-30T09:32:44.210 回答
1

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

但是matplotlib dev应该是兼容的。

您可以使用 matplotlib 和 numpy 索引来实现这一点,而无需使用其他工具。然而 matplotlib 只支持png native

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)

莉娜.png

于 2012-05-30T12:50:07.703 回答