画像があり、元の画像の中点を中心とした元の画像の長方形の領域になる新しい画像をどうにかして取得したいと思います。たとえば、元の画像は1000x1000ピクセルで、元の画像の中央に501x501のサイズの領域を取得したいとします。
Python 3やmatplotlibを使用してそれを行う方法はありますか?
画像があり、元の画像の中点を中心とした元の画像の長方形の領域になる新しい画像をどうにかして取得したいと思います。たとえば、元の画像は1000x1000ピクセルで、元の画像の中央に501x501のサイズの領域を取得したいとします。
Python 3やmatplotlibを使用してそれを行う方法はありますか?
image.crop
PIL ライブラリから
のメソッドは、タスクを実行しているようです: 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()
>>>
現時点では、python 3 用の公式の matplotlib リリースはありません (および PIL はありません)。
ただし、 matplotlib devには互換性があるはずです。
他のツールを使用せずに、matplotlib と numpy のインデックス作成を使用してこれを実現できます。ただし、matplotlib はネイティブで pngのみをサポートします。
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)