【问题标题】:Select image region (programmatically!): Python 3, matplotlib选择图像区域(以编程方式!):Python 3,matplotlib
【发布时间】:2012-05-30 08:19:37
【问题描述】:

我有一个图像,想以某种方式获得一个新图像,它将是原始图像的一个矩形区域,以原始图像的中点为中心。比如说,原始图像是 1000x1000 像素,我想在原始图像的中心获取大小为 501x501 的区域。

有什么方法可以使用 Python 3 和/或 matplotlib?

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    PIL 库中的 image.crop 方法似乎完成了任务: 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()
    >>> 
    

    【讨论】:

    【解决方案2】:

    目前没有针对 python 3 的官方 matplotlib 版本(也没有 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)
    

    【讨论】:

    • 感谢您提供的好例子!据我了解,如果会给出 jpg,是否需要 PIL?不幸的是,我有 jpg 中的所有图像...有没有办法在 python/matplotlib 中将 jpg 保存为 png 而无需使用 PIL?
    • @Katya 文档说它只支持 png。所以你应该需要 PIL。
    猜你喜欢
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2012-05-22
    • 2011-10-29
    • 1970-01-01
    相关资源
    最近更新 更多