Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
选择图像区域(以编程方式!):Python 3,matplotlib_Python_Python 3.x_Matplotlib - Fatal编程技术网

选择图像区域(以编程方式!):Python 3,matplotlib

选择图像区域(以编程方式!):Python 3,matplotlib,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我有一个图像,想得到一个新的图像,它是原始图像的一个矩形区域,以原始图像的中点为中心。比如说,原始图像是1000x1000像素,我想得到原始图像中心大小为501x501的区域 使用Python 3和/或matplotlib有什么方法可以做到这一点吗?来自PIL库的image.crop方法似乎已经完成了任务: 例如: br@ymir:~/temp$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on li

我有一个图像,想得到一个新的图像,它是原始图像的一个矩形区域,以原始图像的中点为中心。比如说,原始图像是1000x1000像素,我想得到原始图像中心大小为501x501的区域


使用Python 3和/或matplotlib有什么方法可以做到这一点吗?

来自PIL库的
image.crop
方法似乎已经完成了任务:

例如:

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()
>>> 

目前还没有Python3的官方matplotlib版本(也没有PIL)

但是,它们应该是兼容的

您可以使用matplotlib和numpy索引来实现这一点,而无需使用其他工具。 但是,matplotlib仅支持


显然,有一些python-3 PIL端口,请参见此处:和此处:很高兴知道,但我会尽量少使用库。我已经在使用matplotlib了,所以我将尝试检查基于matplotlib的建议解决方案。感谢您提供的好示例!据我所知,如果给予jpg,是否需要PIL?不幸的是,我在jpg的所有图像。。。有没有办法在python/matplotlib中将jpg保存为png而不使用PIL?@Katya文档说它只支持png。所以你应该需要PIL。
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)