在matplotlib sub中显示实际大小不同的图像

2024-04-30 03:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python和matplotlib开发一些图像处理算法。我想用一个子块(例如,输出图像旁边的原始图像)在图形中显示原始图像和输出图像。输出图像的大小与原始图像不同。我想让子块以实际大小(或均匀缩放)显示图像,以便我可以比较“苹果对苹果”。我目前使用:

plt.figure()
plt.subplot(2,1,1)
plt.imshow(originalImage)
plt.subplot(2,1,2)
plt.imshow(outputImage)
plt.show()

结果是我得到了子块,但是两个图像都被缩放,因此它们的大小相同(尽管输出图像上的轴与输入图像上的轴不同)。明确地说:如果输入图像是512x512,输出图像是1024x1024,那么两个图像都显示为相同的大小。

有没有办法强制matplotlib以其各自的实际大小显示图像(更好的解决方案,这样matplotlib的动态重缩放不会影响显示的图像)或缩放图像,使其以与其实际大小成比例的大小显示?


Tags: 图像苹果算法图形matplotlibshowplt图像处理
3条回答

如果您希望以实际大小显示图像,因此子块中的两个图像的实际像素大小相同,那么您可能只想使用子块定义中的选项sharexsharey

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 7), dpi=80, sharex=True, sharey=True)
ax[1].imshow(image1, cmap='gray')
ax[0].imshow(image2, cmap='gray')

结果:

enter image description here

其中第二个图像是第一个图像的1/2大小。

修改Joseph的答案:显然默认dpi改为100,所以为了将来的安全,您可以直接从rcParams访问dpi

import matplotlib as mpl

def display_image_in_actual_size(im_path):

    dpi = mpl.rcParams['figure.dpi']
    im_data = plt.imread(im_path)
    height, width, depth = im_data.shape

    # What size does the figure need to be in inches to fit the image?
    figsize = width / float(dpi), height / float(dpi)

    # Create a figure of the right size with one axes that takes up the full figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([0, 0, 1, 1])

    # Hide spines, ticks, etc.
    ax.axis('off')

    # Display the image.
    ax.imshow(im_data, cmap='gray')

    plt.show()

display_image_in_actual_size("./your_image.jpg")

这就是你想要的答案:

def display_image_in_actual_size(im_path):

    dpi = 80
    im_data = plt.imread(im_path)
    height, width, depth = im_data.shape

    # What size does the figure need to be in inches to fit the image?
    figsize = width / float(dpi), height / float(dpi)

    # Create a figure of the right size with one axes that takes up the full figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([0, 0, 1, 1])

    # Hide spines, ticks, etc.
    ax.axis('off')

    # Display the image.
    ax.imshow(im_data, cmap='gray')

    plt.show()

display_image_in_actual_size("./your_image.jpg")

改编自here

相关问题 更多 >