Reputation: 1723
I have an image and want to get somehow a new image which will be a rectangle region of the original image centered at the middle point of the original image. Say, the original image is 1000x1000 pixels and I want to get the region of the size 501x501 in the center the original image.
Any way to do it using Python 3 and/or matplotlib?
Upvotes: 1
Views: 5929
Reputation: 26070
The image.crop
method from the PIL library seems to be up the task:
http://effbot.org/imagingbook/image.htm
For example:
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()
>>>
Upvotes: 2
Reputation: 36214
At the moment there is no official matplotlib release for python 3 (and no PIL).
However matplotlib dev should be compatible.
You can use matplotlib and numpy indexing to achieve this without using other tools. However matplotlib only supports 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)
Upvotes: 1