使用 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)])
这是丑陋的结果。
如何让所有图片具有相同的垂直尺寸?
最佳答案
您发布的代码不适合我。 行
和列
未定义。我跑了:
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
结果:
所以我无法重现这个问题(并假设其他人也不能)。也许这段代码解决了您的问题?祝你好运!
更新
在 @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()
产量:
它基本上只是拉伸(stretch)图像以适应您指定的范围
范围,我相信这本质上只是纵横比。这是否是扭曲您的图像以适应与其他图像相同的尺寸的理想效果?
关于python - 在子图中裁剪 matplotlib 图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503322/