1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ekaterina Mishina
  • 1,633
  • 5
  • 20
  • 23

2 Answers2

2

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()
>>> 
Jonathan Root
  • 535
  • 2
  • 14
  • 31
ev-br
  • 24,968
  • 9
  • 65
  • 78
  • 2
    Apparently, there are some python-3 PIL ports, see here: http://stackoverflow.com/questions/3896286/image-library-for-python-3 and here: http://stackoverflow.com/questions/6188552/are-there-image-processing-modules-for-python-3 – ev-br May 30 '12 at 12:31
  • Good to know, but I would try to use as few libraries as possible. I already use matplotlib, so will try to check the suggested solution based on matplotlib. – Ekaterina Mishina May 30 '12 at 14:55
1

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)

lena.png

bmu
  • 35,119
  • 13
  • 91
  • 108
  • Thanks for the good example! As I understand if jpg will be given, PIL is required? Unfortunately I have all images in jpg... Is there any way to save jpg as png within python/matplotlib without using PIL? – Ekaterina Mishina May 30 '12 at 15:26
  • @Katya the docs say it only supports png. so you should need PIL. – bmu May 30 '12 at 15:42