在子图中裁剪matplotlib图片

时间:2019-04-03 19:56:44

标签: python matplotlib

使用python和matplotlib裁剪图片似乎很容易(请参见this SO question)。但是,在带有子图的图中裁剪一个图形时,图片的整体大小会发生变化。我正在粘贴示例和意外的结果:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('http://res.freestockphotos.biz/pictures/15/15912-illustration-of-a-banana-pv.png')
fig=plt.figure(figsize=(18, 4))

for i in range(1, 4):
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
    if i > 2:
        plt.imshow(img[:img.shape[0],:int(img.shape[1]/2)])

这是丑陋的结果。

enter image description here

如何使所有图片的垂直尺寸相同?

1 个答案:

答案 0 :(得分:1)

您发布的代码无法为我运行。 rowscolumns未定义。我跑了:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('http://res.freestockphotos.biz/pictures/15/15912-illustration-of-a-banana-pv.png')
fig = plt.figure(figsize=(18, 4))

rows = 1 # I added this
columns = 3 # and this
for i in range(1, 4):
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
    if i > 2:
        plt.imshow(img[:img.shape[0], :int(img.shape[1] / 2)])

plt.show() # and this

结果:

output

因此,我无法重现该问题(并假设其他人也不能)。也许这段代码解决了您的问题?祝你好运!

更新

在@ImportanceOfBeingErnest后面的注释列应该为6,我弄弄了它,也许您正在寻找extent设置?我跑了

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('http://res.freestockphotos.biz/pictures/15/15912-illustration-of-a-banana-pv.png')
fig = plt.figure(figsize=(18, 4))

rows = 1
columns = 6
for i in range(1, 4):
    fig.add_subplot(rows, columns, i)
    if i > 2:
        plt.imshow(img[:img.shape[0], :int(img.shape[1] / 2)], extent=(0, 50, 0, 50))
    else:
        plt.imshow(img, extent=(0, 50, 0, 50))
plt.tight_layout()
plt.show()

屈服:

new output

基本上,它只是拉伸图像以适合您指定的extent范围,我认为这实际上只是宽高比。是使您的图像变形到与其他图像相同大小的理想效果吗?

相关问题