我有一個圖像,並想以某種方式得到一個新的圖像,這將是原始圖像的中間點原始圖像的矩形區域。比方說,原始圖像是1000x1000像素,我想在原始圖像的中心獲取大小爲501x501的區域。選擇圖像區域(編程!):Python 3,matplotlib
任何使用Python 3和/或matplotlib的方法?
我有一個圖像,並想以某種方式得到一個新的圖像,這將是原始圖像的中間點原始圖像的矩形區域。比方說,原始圖像是1000x1000像素,我想在原始圖像的中心獲取大小爲501x501的區域。選擇圖像區域(編程!):Python 3,matplotlib
任何使用Python 3和/或matplotlib的方法?
從PIL庫image.crop
方法似乎是出任務: http://effbot.org/imagingbook/image.htm
例如:
[email protected]:~/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()
>>>
在沒有正式matplotlib釋放蟒蛇3的時刻(沒有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)
謝謝,但PIL是Python的2只... – Katya
顯然,有一些Python-3 PIL港口,在這裏看到:http://stackoverflow.com/questions/3896286/ image-library-for-python-3和這裏:http://stackoverflow.com/questions/6188552/are-there-image-processing-modules-for-python-3 –
很高興知道,但我會嘗試使用盡可能少的圖書館。我已經使用matplotlib,所以會嘗試檢查基於matplotlib的建議解決方案。 – Katya