在matplotlib子图中显示具有实际大小的不同图像

Doo*_*oov 9 python image matplotlib

我正在使用python和matplotlib处理一些图像处理算法.我想使用子图(例如输出图像旁边的原始图像)在图中显示原始图像和输出图像.输出图像的尺寸与原始图像的尺寸不同.我想让子图以实际尺寸显示图像(或统一缩放),以便我可以比较"苹果与苹果".我目前使用:

plt.figure()
plt.subplot(2,1,1)
plt.imshow(originalImage)
plt.subplot(2,1,2)
plt.imshow(outputImage)
plt.show()
Run Code Online (Sandbox Code Playgroud)

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

有没有办法强制matplotlib以各自的实际尺寸显示图像(优选的解决方案,以便matplotlib的动态重新缩放不会影响显示的图像)或缩放图像,使其显示尺寸与其实际尺寸成比例?

Jos*_*eph 14

这是您正在寻找的答案:

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")
Run Code Online (Sandbox Code Playgroud)

改编自这里.

  • 该问题询问在一张图中并排显示两个图像的情况。 (2认同)

Ben*_*ier 8

在此处调整约瑟夫的回答:显然默认 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")
Run Code Online (Sandbox Code Playgroud)

  • 这很有用,但可能更短,只需说可以使用 `dpi = matplotlib.rcParams['figure.dpi']` 访问默认 dpi (6认同)

MrE*_*MrE 8

如果您希望以实际大小显示图像,因此子图中两个图像的实际像素大小相同,您可能只想使用选项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')
Run Code Online (Sandbox Code Playgroud)

结果是:

在此处输入图片说明

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