【问题标题】:Displaying different images with actual size in matplotlib subplot在 matplotlib 子图中显示具有实际大小的不同图像
【发布时间】:2015-03-02 17:35:59
【问题描述】:

我正在使用 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 的动态重新缩放不会影响显示的图像)或缩放图像,使它们以成比例的大小显示他们的实际尺寸?

【问题讨论】:

  • 我认为figimage 可能对您有用...这个问题可能与this 问题重复...
  • 谢谢。我会看看。是的,看起来像一个重复的帖子。我想我在搜索时没有看到那个。谢谢!
  • 使用 sharexsharey 共享轴。请参阅下面的答案

标签: python image matplotlib


【解决方案1】:

这是您正在寻找的答案:

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

【讨论】:

  • 本题问的是在一张图中并排显示两张图片的情况。
【解决方案2】:

在这里调整约瑟夫的回答:显然默认 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")

【讨论】:

  • 这很有用,但可能会更短,只需说可以使用 dpi = matplotlib.rcParams['figure.dpi'] 访问默认 dpi 即可
【解决方案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')

结果:

第二张图片的大小是第一张的 1/2。

【讨论】:

  • 如何为每个情节添加标题?
  • 取eaxh ax[n]对象并使用title函数
  • 如何调整小图片的轴以匹配其较小的尺寸?
  • 什么意思?这里的技巧使用 sharex 和 sharey 来共享轴,以便图像以正确的比例显示。也就是说,相同的轴 = 实际像素大小。
  • 另一个技巧是使用较大的图片last调用imshow,因为这将定义两个图的宽度/高度。对吗?
猜你喜欢
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多